package util import ( "crypto/tls" "github.com/valyala/fasthttp" "net" "time" ) const ( MediaTypeJSON = "application/json" MediaTypeXML = "application/xml" MediaTypeForm = "application/x-www-form-urlencoded" MediaTypeMultipartForm = "multipart/form-data" MediaTypeOctetStream = "application/octet-stream" MediaTypeHTML = "text/html" MediaTypePlain = "text/plain" MediaTypeJavascript = "application/javascript" MediaTypeCSS = "text/css" MediaTypeGIF = "image/gif" MediaTypeJPEG = "image/jpeg" MediaTypePNG = "image/png" MediaTypeBMP = "image/bmp" MediaTypeIcon = "image/x-icon" MediaTypePDF = "application/pdf" MediaTypeZip = "application/zip" MediaTypeTAR = "application/x-tar" MediaTypeGZ = "application/x-gzip" MediaTypeProtobuf = "application/protobuf" MediaTypeGRPC = "application/grpc" ) // Request 包装fasthttp的请求工具 /* 请求示例 1.GET请求 Request("https://httpbin.org/get", http.MethodGet, nil, map[string]string{"Cookie": "token=e69f5609-378f-4461-89d0-7508f2a06022"}) 2.POST请求 Request("https://httpbin.org/post", http.MethodPost, body, map[string]string{"Content-Type": MediaTypeJSON}) 3.PUT请求 Request("https://httpbin.org/put", http.MethodPut, body, map[string]string{ "Content-Type": MediaTypeJSON, "Cookie": "aweToken=3ab9f63f-b0b3-4935-80ec-405d76ac111d", }) */ func Request(url string, method string, body []byte, headers map[string]string) ([]byte, error) { req := fasthttp.AcquireRequest() defer fasthttp.ReleaseRequest(req) req.SetRequestURI(url) req.Header.SetMethod(method) // 设置默认请求头部 req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.0.0 Safari/537.36") // 设置请求头部 for k, v := range headers { req.Header.Set(k, v) } // 设置请求体 if body != nil { req.SetBody(body) } // 创建一个忽略证书问题的客户端 client := &fasthttp.Client{ Dial: func(addr string) (net.Conn, error) { return net.DialTimeout("tcp", addr, 30*time.Second) }, TLSConfig: &tls.Config{ InsecureSkipVerify: true, }, } resp := fasthttp.AcquireResponse() defer fasthttp.ReleaseResponse(resp) // 发送请求 if err := client.Do(req, resp); err != nil { return nil, err } // 返回响应体和错误信息 return resp.Body(), nil }