A nicer interface for golang stdlib HTTP client
Because golang HTTP client is a pain in the a...
- Compatible with golang
httpstdlib:http.Request,http.Responseandhttp.Cookie - Step by step to build your request
- Better HTTP client
- Better cookie jar
- Import/export allow we save/transfer requests in JSON
- Default setting: example default
User-AgentorAccept-Language
go get -u github.com/ddo/rqimport"net/http"import"github.com/ddo/rq"r:=rq.Get("https://httpbin.org/get")
// query https://httpbin.org/get?q=1&q=2&q=3&_=123456r.Qs("q", "1", "2")
r.Qs("q", "3")
r.Qs("_", "123456")
// send with golang default HTTP clientres, err:=http.DefaultClient.Do(r.ParseRequest())
deferres.Body.Close()In case you did not know that golang default http.Client has no timeout.
use rq/client which has 180s timeout by default
import"github.com/ddo/rq"import"github.com/ddo/rq/client"r:=rq.Post("https://httpbin.org/post")
// queryr.Qs("_", "123456")
// Formr.Send("data", "data value")
r.Send("extra", "extra value")
// use default rq client// true to tell #Send to read all the response boby when returndata, res, err:=client.Send(r, true)
// no need to close res.Body// read = false -> you need to call res.Body when done readingr:=rq.Post("https://httpbin.org/post")
r.Set("Content-Type", "application/json")
r.Set("User-Agent", "ddo/rq")r:=rq.Post("https://httpbin.org/post")
r.SendRaw(strings.NewReader("raw data binary or json"))// by default timeout = 3min// no cookie jar// and stops after 10 consecutive requests (10 redirects)customClient:=client.New(nil)import"github.com/ddo/rq/client/jar"cookieJar:=jar.New()
// custom timeout = 10s and cookie jarcustomClient:=client.New(&Option{
Timeout: time.Second*10,
jar: cookieJar,
})// set default User-AgentdefaultRq:=rq.Get("")
defaultRq.Set("User-Agent", "github.com/ddo/rq")
customClient:=client.New(&Option{
DefaultRq: defaultRq,
})
// from now all the requests called via this customClient// gonna have the User-Agent header = "github.com/ddo/rq"// if User-Agent header in request is not set- Default
clientstops after 10 consecutive requests - Or you can use
client.NoRedirectto disable redirect
client.New(&Option{
CheckRedirect: client.NoCheckRedirect,
})import"github.com/ddo/rq/client/jar"cookieJar:=jar.New()
customClient:=client.New(&client.Option{
Jar: cookieJar,
})
// get all cookies by hostnamecookies, err:=cookieJar.Get("httpbin.org")
// get a cookie by hostname and namecookie, err:=cookieJar.GetByName("httpbin.org", "cookiename").
// set cookieserr:=cookieJar.Set("httpbin.org", cookies)
// set a cookieerr:=cookieJar.SetOne("httpbin.org", cookie)
// clear the cookie jarerr:=cookieJar.Clear("httpbin.org")
// delete a cookie by it's nameerr:=cookieJar.Delete("httpbin.org", "cookiename")Set env DLOG=* to enable logger to see request activities
List here #1