http util for restful request: get, post, put, patch, delete
go get -u github.com/chinaran/httputil
request and response data support: string, []byte, map, struct
http request options
default: &http.Client{}
example: client with https
tr := &http.Transport{
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec
}
client := &http.Client{Transport: tr}
default: 30 * time.Second
default: "Accept": "application/json", "Content-Type": "application/json;charset=UTF-8"
default: json.Marshal
default: json.Unmarshal
default: donot log request time cost, using logger.Printf
log style: gin
example: INFO 2021/05/04 12:24:04 REQUEST | 200 | 305.549239ms | GET https://httpbin.org/get?hello=world
default: defaultCodeJudger
(2xx is the right status code)
package main
import (
"context"
"log"
hu "github.com/chinaran/httputil"
)
func main() {
// get
urlGet := "https://httpbin.org/get?hello=world"
respGetM := map[string]interface{}{}
if err := hu.Get(context.TODO(), urlGet, &respGetM, hu.WithLogTimeCost()); err != nil {
log.Printf("Get %s err: %s", urlGet, err)
return
}
log.Printf("Get %s map response: %+v", urlGet, respGetM)
respGetStr := ""
if err := hu.Get(context.TODO(), urlGet, &respGetStr, hu.WithLogTimeCost()); err != nil {
log.Printf("Get %s err: %s", urlGet, err)
return
}
log.Printf("Get %s string response: %+v", urlGet, respGetStr)
// post
urlPost := "https://httpbin.org/post"
req := map[string]string{"hello": "world"}
respPost := struct {
Data string `json:"data"`
}{}
if err := hu.Post(context.TODO(), urlPost, &req, &respPost, hu.WithLogTimeCost()); err != nil {
log.Printf("Post %s err: %s", urlPost, err)
return
}
log.Printf("Post %s struct response: %+v", urlPost, respPost)
}
result: