Skip to content

gowww/client

Repository files navigation

gowww client GoDoc Build Coverage Go Report Status Testing

Package client provides an HTTP client for clean requests.

Installing

  1. Get package:

    go get -u github.com/gowww/client
  2. Import it in your code:

    import "github.com/gowww/client"

Usage

Request

Use Get, Post, Put, Patch, Delete or Head with the destination URL to initiate a request.
Options are chainable:

file, err := os.Open("data/one.txt")
if err != nil {
	panic(err)
}
defer file.Close()

req := client.Post("http://example.com").
	DisableRedirect().
	ForceMultipart().
	Header("Accept-Language", "en").
	UserAgent("Googlebot/2.1 (+http://www.google.com/bot.html)").
	Cookie(&http.Cookie{Name: "session", Value: "123"}).
	Value("id", "123").
	Value("name", "Doe").
	File("file", "one.txt", file).
	OpenFile("picture", "one.png").
	OpenFile("picture", "two.png")

Finally, use Do to send the requet and get the response or, eventually, the deferred first error of procedure:

res, err := req.Do()
if err != nil {
	panic(err)
}
defer res.Close()

Don't forget to close the response body when done.

Response

A Response wraps the standard http.Response and provides some utility functions.

Use Response.Cookie to retrieve a single cookie:

c, err := res.Cookie(tokenCookieName)
if err != nil {
	// Generally, error is http.ErrNoCookie.
}

Use Response.JSON to decode a JSON body into a variable:

jsres := new(struct{
	ID string `json:"id"`
})
res.JSON(jsres)

Debugging

Debugging a request is pretty simple with Response.Dump.
It prints the request info, writes the body in a file and opens it in your browser.

res, err := client.Get("http://example.com").Do()
if err != nil {
	panic(err)
}
res.Dump()