golang有用的库及工具 之 fasthttp客户端 最通用最有效最简单使用方式

来源:互联网 发布:java socket长连接心跳 编辑:程序博客网 时间:2024/05/25 01:36

fasthttp 是go语言中最常用性能最好的http请求库。

那么如何使用fasthttp 客户端调用http请求。


常用http kv请求:

//http请求func doTimeout(arg *fasthttp.Args, method string, requestURI string, cookies map[string]interface{}) ([]byte, int, error) {   req := &fasthttp.Request{}   switch method {   case "GET":      req.Header.SetMethod(method)      // 拼接url      requestURI = requestURI + "?" + arg.String()   case "POST":      req.Header.SetMethod(method)      arg.WriteTo(req.BodyWriter())   }   if cookies != nil {      for key, v := range cookies {         req.Header.SetCookie(key, v.(string))      }   }   req.SetRequestURI(requestURI)   resp := &fasthttp.Response{}   err := gCli.DoTimeout(req, resp, time.Second*30)   return resp.Body(), resp.StatusCode(),  err}

json body 使用:

func doJsonTimeout(method string, url, bodyjson string) ([]byte, int, error) {   req := &fasthttp.Request{}   resp := &fasthttp.Response{}   switch method {   case "GET":      req.Header.SetMethod(method)   case "POST":      req.Header.SetMethod(method)   }   req.Header.SetContentType("application/json")   req.SetBodyString(bodyjson)   req.SetRequestURI(url)   err := gCli.DoTimeout(req, resp, time.Second*30)   return resp.Body(), resp.StatusCode(),  err}


test:

func main() {   var arg = &fasthttp.Args{}   arg.Set("hello","world")   fmt.Println(doTimeout(arg, "GET","http://127.0.0.1/hello",nil))   fmt.Println(doJsonTimeout("GET","http://127.0.0.1/hello","{\"hello\":\"world\"}"))}