Go HTTP Requests for Humans
go get -u github.com/onesafe/requests
import (
"github.com/onesafe/requests"
)
r := requests.NewRequest()
resp, err := r.Get("https://github.com")
if !resp.isOk(resp.StatusCode) {
return errors.New("Get Failed")
}
r := requests.NewRequest()
r.Datas = requests.DATAS{
"name": "test"
}
resp, err := r.Post("https://www.httpbin.org/post")
or
r := requests.NewRequest()
// requestBody can be any struct (interface{})
res, _ := json.Marshal(requestBody)
r.Body = string(res)
resp, err := r.Post("https://www.httpbin.org/post")
// content type: byte[]
content, err := resp.Content()
// text type: string
text, err := resp.Text()
// data type can be: map[string]interface{}
var data map[string]string
err = resp.Json(&data)
- Set Headers
- Set Params
- Set TimeOut
- Authentication
- Set Proxy
- Set Pool Size
- Hooks
- Cookies
r := requests.NewRequest()
r.Headers = requests.HEADERS{
"Referer": "http://github.com",
"Accept-Language": "zh-CN,zh;",
"Content-Type": requests.ContentTypeJsonType,
}
resp, err := r.Get("https://www.baidu.com")
r := requests.NewRequest()
r.Params = requests.PARAMS{
"user": "onesafe",
}
resp, err := r.Get("https://github.com")
r := requests.NewRequest()
r.SetTimeout(10) // 10 Seconds
resp, err := r.Get("https://github.com")
r := requests.NewRequest()
r.BasicAuth = requests.BasicAuth{"user", "passwd"}
resp, err := r.Get("http://httpbin.org/basic-auth/user/passwd")
r := requests.NewRequest()
// use proxyUrl as your proxy
r.Proxy = proxyUrl
resp, err := r.Get("http://httpbin.org/get")
r := requests.NewRequest()
r.SetPoolSize(30) // Default Pool Size is 10 (int)
resp, err := r.Get("http://github.com")
// You can use your own struct to implements this two functions
// BeforeRequest will call before send http request
BeforeRequest(req *http.Request) (resp *http.Response, err error)
// AfterRequest will call after got response
AfterRequest(req *http.Request, resp *http.Response, err error) (newResp *http.Response, newErr error)
type hookNothing struct {
callBeforeHook bool
callAfterHook bool
}
func (h *hookNothing) BeforeRequest(req *http.Request) (resp *http.Response, err error) {
h.callBeforeHook = true
return
}
func (h *hookNothing) AfterRequest(req *http.Request, resp *http.Response, err error) (newResp *http.Response, newErr error) {
h.callAfterHook = true
return
}
r := requests.NewRequest()
r.Hooks = []requests.Hook{h}
resp, _ := r.Get("https://httpbin.org/get")
Set Cookies
r := requests.NewRequest()
r.Cookies = requests.COOKIES{
"key": "value",
"a": "123",
}
resp, _ := r.Get("https://httpbin.org/cookies")
Get Cookies
r := requests.NewRequest()
resp, _ := r.Get("https://www.httpbin.org")
coo := resp.Cookies()
for _, c := range coo {
fmt.Println(c.Name, c.Value)
}