Skip to content

Result ​

Result wraps the HTTP response and request metadata and provides nil-safe access methods. It is returned by Client.Request() or the package-level functions.

go
type Result struct {
    Request  *RequestInfo
    Response *ResponseInfo
    Meta     *RequestMeta
}

Fields ​

FieldTypeDescription
Result.Request*RequestInfoDetails of the request as finally sent (after redirects); nil-safe methods check it automatically
Result.Response*ResponseInfoFinal response data; nil when the request errored
Result.Meta*RequestMetaRequest-execution metadata (duration, attempts, proxy, redirect chain); nil only in zero-value Results constructed by callers

Method Overview ​

All methods are defined on the *Result pointer receiver and are nil-receiver-safe: they return zero values instead of panicking.

MethodSignatureDescription
Result.StatusCodefunc (r *Result) StatusCode() intReturns the HTTP status code; nil-safe, returns 0
Result.Bodyfunc (r *Result) Body() stringReturns the response body as a string; nil-safe, returns an empty string
Result.RawBodyfunc (r *Result) RawBody() []byteReturns the raw response-body bytes; nil-safe, returns nil
Result.Protofunc (r *Result) Proto() stringReturns the HTTP protocol version (e.g. "HTTP/1.1")
Result.IsSuccessfunc (r *Result) IsSuccess() boolReturns true when the status code is 2xx
Result.IsRedirectfunc (r *Result) IsRedirect() boolReturns true when the status code is 3xx
Result.IsClientErrorfunc (r *Result) IsClientError() boolReturns true when the status code is 4xx
Result.IsServerErrorfunc (r *Result) IsServerError() boolReturns true when the status code is 5xx
Result.Unmarshalfunc (r *Result) Unmarshal(v any) errorParses the JSON response body into v
Result.SaveToFilefunc (r *Result) SaveToFile(filePath string) errorWrites the response body to a file
Result.Stringfunc (r *Result) String() stringReturns a human-readable string representation (sensitive headers masked)
Result.ResponseCookiesfunc (r *Result) ResponseCookies() []*http.CookieReturns all cookies from the response
Result.GetCookiefunc (r *Result) GetCookie(name string) *http.CookieReturns the named response cookie, or nil if absent
Result.HasCookiefunc (r *Result) HasCookie(name string) boolReturns whether the response contains the named cookie
Result.RequestCookiesfunc (r *Result) RequestCookies() []*http.CookieReturns all cookies sent with the request
Result.GetRequestCookiefunc (r *Result) GetRequestCookie(name string) *http.CookieReturns the named request cookie, or nil if absent
Result.HasRequestCookiefunc (r *Result) HasRequestCookie(name string) boolReturns whether the request contains the named cookie
go
result, err := httpc.Get("https://api.example.com/users/1")
if err != nil {
    log.Fatal(err)
}

fmt.Println(result.StatusCode()) // 200
fmt.Println(result.Body())       // {"id":1,"name":"test"}

TIP

Result is created fresh for each request and reclaimed by GC; no manual release is needed.

Access style

Prefer the nil-safe accessor methods (StatusCode, Body, GetCookie, etc.). The Request/Response/Meta fields are exported mainly so tests and mocks can construct a Result directly. Before reading them off a client-returned Result, nil-check the nested pointers: Response is nil when the request failed.

Basic Methods ​

StatusCode ​

go
func (r *Result) StatusCode() int

Returns the HTTP status code. Nil-safe: returns 0.

Body ​

go
func (r *Result) Body() string

Returns the response body as a string. Nil-safe: returns an empty string.

RawBody ​

go
func (r *Result) RawBody() []byte

Returns the response body as raw bytes. Nil-safe: returns nil.

Proto ​

go
func (r *Result) Proto() string

Returns the HTTP protocol version, e.g. "HTTP/1.1", "HTTP/2.0".

Status Checks ​

IsSuccess ​

go
func (r *Result) IsSuccess() bool

Returns true when the status code is 2xx.

IsRedirect ​

go
func (r *Result) IsRedirect() bool

Returns true when the status code is 3xx.

IsClientError ​

go
func (r *Result) IsClientError() bool

Returns true when the status code is 4xx.

IsServerError ​

go
func (r *Result) IsServerError() bool

Returns true when the status code is 5xx.

go
result, _ := client.Get(url)
switch {
case result.IsSuccess():
    handleSuccess(result)
case result.IsClientError():
    handleClientError(result)
case result.IsServerError():
    handleServerError(result)
}

ResponseCookies ​

go
func (r *Result) ResponseCookies() []*http.Cookie

Returns all cookies from the response.

GetCookie ​

go
func (r *Result) GetCookie(name string) *http.Cookie

Returns the named response cookie, or nil if absent.

go
cookie := result.GetCookie("session")
if cookie != nil {
    fmt.Println(cookie.Value)
}

HasCookie ​

go
func (r *Result) HasCookie(name string) bool

Returns whether the response contains the named cookie.

RequestCookies ​

go
func (r *Result) RequestCookies() []*http.Cookie

Returns all cookies sent with the request.

GetRequestCookie ​

go
func (r *Result) GetRequestCookie(name string) *http.Cookie

Returns the named request cookie, or nil if absent.

HasRequestCookie ​

go
func (r *Result) HasRequestCookie(name string) bool

Returns whether the request contains the named cookie.

JSON Parsing ​

Unmarshal ​

go
func (r *Result) Unmarshal(v any) error

Parses the JSON response body into v, following json.Unmarshal conventions.

ErrorTrigger Condition
ErrResponseBodyEmptyThe response body is empty (including when Result or Response is nil)
ErrResponseBodyTooLargeThe response body exceeds the 50MB JSON-parsing limit (the error reports the actual byte count)
go
var user User
if err := result.Unmarshal(&user); err != nil {
    log.Fatal(err)
}
fmt.Println(user.Name)

File Saving ​

SaveToFile ​

go
func (r *Result) SaveToFile(filePath string) error

Writes the response body to a file, unconditionally overwriting an existing target (unlike Download, which returns ErrFileExists by default). The file path is security-validated (path-traversal protection, symlink checks, system-path protection). Content is first written to a <path>.httpc-tmp temporary file and atomically renamed into place once validation passes; the file is written with 0644 permissions.

ErrorTrigger Condition
ErrResponseBodyEmptyThe response body is nil or empty (including when Result or Response is nil)
ErrDownloadInProgressA Download or another SaveToFile in the same process is already writing the same target path
Wrapped errorPath validation failed or the write failed
go
result, _ := client.Get("https://example.com/data.csv")

if err := result.SaveToFile("/tmp/data.csv"); err != nil {
    log.Fatal(err)
}

String Representation ​

String ​

go
func (r *Result) String() string

String returns a human-readable string representation (it implements fmt.Stringer). Sensitive headers are masked automatically. The response body content is never included: only its size in bytes is reported (Body: [N bytes omitted]), which keeps credentials and session data out of logs. A nil Result, or one without a response, yields Result{}.

Masked headers: Authorization, Cookie, Set-Cookie, X-Api-Key, X-Auth-Token, and Proxy-Authorization, shown in the header list as Name: ***.

go
result, _ := client.Get(url)
fmt.Println(result.String())
// Result{Status: 200 200 OK, ContentLength: 1024, Duration: 125ms, Attempts: 1, ...}

Sub-types ​

RequestInfo ​

go
type RequestInfo struct {
    URL     string
    Method  string
    Headers http.Header
    Cookies []*http.Cookie
}

Request details. Accessed via result.Request.

FieldTypeDescription
RequestInfo.URLstringRequest URL
RequestInfo.MethodstringHTTP method
RequestInfo.Headershttp.HeaderRequest headers
RequestInfo.Cookies[]*http.CookieRequest cookies

ResponseInfo ​

go
type ResponseInfo struct {
    StatusCode    int
    Status        string
    Proto         string
    Headers       http.Header
    Body          string
    RawBody       []byte
    ContentLength int64
    Cookies       []*http.Cookie
}

Response data. Accessed via result.Response.

FieldTypeDescription
ResponseInfo.StatusCodeintHTTP status code
ResponseInfo.StatusstringStatus text (e.g. "200 OK")
ResponseInfo.ProtostringHTTP protocol version
ResponseInfo.Headershttp.HeaderResponse headers
ResponseInfo.BodystringResponse body (string)
ResponseInfo.RawBody[]byteResponse body (raw bytes)
ResponseInfo.ContentLengthint64Response Content-Length
ResponseInfo.Cookies[]*http.CookieResponse cookies

RequestMeta ​

go
type RequestMeta struct {
    Duration      time.Duration
    Attempts      int
    ProxyURL      string
    RedirectChain []string
    RedirectCount int
}

Request-execution metadata. Accessed via result.Meta.

FieldDescription
RequestMeta.DurationTotal time from request start to response completion
RequestMeta.AttemptsTotal attempts including retries
RequestMeta.ProxyURLProxy URL used by the attempt that produced the current response (Connection.ProxyURL or the selected proxy-pool entry). Empty for direct connections and for system proxies (EnableSystemProxy); configure Connection.ProxyURL or ProxyPool explicitly when you need to observe egress per request
RequestMeta.RedirectChainChain of redirect URLs followed
RequestMeta.RedirectCountNumber of redirects followed
go
result, _ := client.Get(url)

fmt.Println(result.Meta.Duration)      // 125ms
fmt.Println(result.Meta.Attempts)       // 2 (retried once)
fmt.Println(result.Meta.RedirectCount)  // 1 (followed one redirect)
fmt.Println(result.Meta.ProxyURL)        // "" (direct) or "http://proxy:8080"

Complete Example ​

go
package main

import (
	"fmt"
	"log"

	"github.com/cybergodev/httpc"
)

func main() {
	result, err := httpc.Get("https://api.example.com/users/1")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(result.StatusCode()) // 200
	fmt.Println(result.IsSuccess())  // true

	var user struct {
		Name string `json:"name"`
	}
	if err := result.Unmarshal(&user); err != nil {
		log.Fatal(err)
	}
	fmt.Println(user.Name) // test

	fmt.Println(result.Meta.Attempts) // 1
}

See Also ​