您好,登錄后才能下訂單哦!
小編給大家分享一下Golang如何請求fasthttp,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
首先分享一下基礎的用法封裝:
PS:這個屬于練習版本,所以沒寫多少注釋。
package ft import ( "encoding/json" "fmt" "funtester/task" "github.com/valyala/fasthttp" ) func FastGet(url string, args map[string]interface{}) ([]byte, error) { uri := url + "?" + task.ToValues(args) _, resp, err := fasthttp.Get(nil, uri) if err != nil { fmt.Println("請求失敗:", err.Error()) return nil, err } return resp, err } func FastPostForm(url string, args map[string]interface{}) ([]byte, error) { // 填充表單,類似于net/url params := &fasthttp.Args{} for s, i2 := range args { sprintf := fmt.Sprintf("%v", i2) params.Add(s, sprintf) } _, resp, err := fasthttp.Post(nil, url, params) if err != nil { fmt.Println("請求失敗:", err.Error()) return nil, err } return resp, nil } func FastPostJson(url string, args map[string]interface{}) ([]byte, error) { req := &fasthttp.Request{} req.SetRequestURI(url) marshal, _ := json.Marshal(args) req.SetBody(marshal) // 默認是application/x-www-form-urlencoded,其實無所謂 req.Header.SetContentType("application/json") req.Header.SetMethod("POST") resp := &fasthttp.Response{} if err := fasthttp.Do(req, resp); err != nil { fmt.Println("請求失敗:", err.Error()) return nil, err } return resp.Body(), nil }
其中兩點主要注意:
FastGet、FastPostForm使用的fasthttp提供的默認獲取請求的方式,FastPostJson使用了自定義請求和獲取響應的方式
關于請求頭中的req.Header.SetContentType方法,其實無所謂,服務端都可以解析
下面分享使用更高的性能(基于對象池)的API創建請求和獲取響應的方式:
package task import ( "crypto/tls" "encoding/json" "fmt" "github.com/valyala/fasthttp" "log" "time" ) var FastClient fasthttp.Client = fastClient() // FastGet 獲取GET請求對象,沒有進行資源回收 // @Description: // @param url // @param args // @return *fasthttp.Request func FastGet(url string, args map[string]interface{}) *fasthttp.Request { req := fasthttp.AcquireRequest() req.Header.SetMethod("GET") values := ToValues(args) req.SetRequestURI(url + "?" + values) return req } // FastPostJson POST請求JSON參數,沒有進行資源回收 // @Description: // @param url // @param args // @return *fasthttp.Request func FastPostJson(url string, args map[string]interface{}) *fasthttp.Request { req := fasthttp.AcquireRequest() // 默認是application/x-www-form-urlencoded req.Header.SetContentType("application/json") req.Header.SetMethod("POST") req.SetRequestURI(url) marshal, _ := json.Marshal(args) req.SetBody(marshal) return req } // FastPostForm POST請求表單傳參,沒有進行資源回收 // @Description: // @param url // @param args // @return *fasthttp.Request func FastPostForm(url string, args map[string]interface{}) *fasthttp.Request { req := fasthttp.AcquireRequest() // 默認是application/x-www-form-urlencoded //req.Header.SetContentType("application/json") req.Header.SetMethod("POST") req.SetRequestURI(url) marshal, _ := json.Marshal(args) req.BodyWriter().Write([]byte(ToValues(args))) req.BodyWriter().Write(marshal) return req } // FastResponse 獲取響應,保證資源回收 // @Description: // @param request // @return []byte // @return error func FastResponse(request *fasthttp.Request) ([]byte, error) { response := fasthttp.AcquireResponse() defer fasthttp.ReleaseResponse(response) defer fasthttp.ReleaseRequest(request) if err := FastClient.Do(request, response); err != nil { log.Println("響應出錯了") return nil, err } return response.Body(), nil } // DoGet 發送GET請求,獲取響應 // @Description: // @param url // @param args // @return []byte // @return error func DoGet(url string, args map[string]interface{}) ([]byte, error) { req := fasthttp.AcquireRequest() defer fasthttp.ReleaseRequest(req) // 用完需要釋放資源 req.Header.SetMethod("GET") values := ToValues(args) req.SetRequestURI(url + "?" + values) resp := fasthttp.AcquireResponse() defer fasthttp.ReleaseResponse(resp) // 用完需要釋放資源 if err := FastClient.Do(req, resp); err != nil { fmt.Println("請求失敗:", err.Error()) return nil, err } return resp.Body(), nil } // fastClient 獲取fast客戶端 // @Description: // @return fasthttp.Client func fastClient() fasthttp.Client { return fasthttp.Client{ Name: "FunTester", NoDefaultUserAgentHeader: true, TLSConfig: &tls.Config{InsecureSkipVerify: true}, MaxConnsPerHost: 2000, MaxIdleConnDuration: 5 * time.Second, MaxConnDuration: 5 * time.Second, ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second, MaxConnWaitTimeout: 5 * time.Second, } }
用的還是moco_FunTester測試框架,腳本如下:
package com.mocofun.moco.main import com.funtester.utils.ArgsUtil import com.mocofun.moco.MocoServer import org.apache.tools.ant.taskdefs.condition.And class Share extends MocoServer { static void main(String[] args) { def util = new ArgsUtil(args) // def server = getServerNoLog(util.getIntOrdefault(0,12345)) def server = getServer(util.getIntOrdefault(0, 12345)) server.get(both(urlStartsWith("/test"),existArgs("code"))).response("get請求") server.post(both(urlStartsWith("/test"), existForm("fun"))).response("post請求form表單") server.post(both(urlStartsWith("/test"), existParams("fun"))).response("post請求json表單") server.get(urlStartsWith("/qps")).response(qps(textRes("恭喜到達QPS!"), 1)) // server.response(delay(jsonRes(getJson("Have=Fun ~ Tester !")), 1000)) server.response("Have Fun ~ Tester !") def run = run(server) waitForKey("fan") run.stop() } }
第一次寫Golang單測,有點不適應,搞了很久才通。
package test import ( "funtester/ft" "funtester/task" "log" "testing" ) const url = "http://localhost:12345/test" func args() map[string]interface{} { return map[string]interface{}{ "code": 32, "fun": 32, "msg": "324", } } func TestGet(t *testing.T) { get := task.FastGet(url, args()) res, err := task.FastResponse(get) if err != nil { t.Fail() } v := string(res) log.Println(v) if v != "get請求" { t.Fail() } } func TestPostJson(t *testing.T) { post := task.FastPostJson(url, args()) res, err := task.FastResponse(post) if err != nil { t.Fail() } v := string(res) log.Println(v) if v != "post請求json表單" { t.Fail() } } func TestPostForm(t *testing.T) { post := task.FastPostForm(url, args()) res, err := task.FastResponse(post) if err != nil { t.Fail() } v := string(res) log.Println(v) if v != "post請求form表單" { t.Fail() } } func TestGetNor(t *testing.T) { res, err := ft.FastGet(url, args()) if err != nil { t.Fail() } v := string(res) log.Println(v) if v != "get請求" { t.Fail() } } func TestPostJsonNor(t *testing.T) { res, err := ft.FastPostJson(url, args()) if err != nil { t.Fail() } v := string(res) log.Println(v) if v != "post請求json表單" { t.Fail() } } func TestPostFormNor(t *testing.T) { res, err := ft.FastPostForm(url, args()) if err != nil { t.Fail() } v := string(res) log.Println(v) if v != "post請求form表單" { t.Fail() } }
用的自帶的控制臺輸出內容:
=== RUN TestGet
2021/10/18 18:56:49 get請求
--- PASS: TestGet (0.01s)
=== RUN TestPostJson
2021/10/18 18:56:49 post請求json表單
--- PASS: TestPostJson (0.00s)
=== RUN TestPostForm
2021/10/18 18:56:49 post請求form表單
--- PASS: TestPostForm (0.00s)
=== RUN TestGetNor
2021/10/18 18:56:49 get請求
--- PASS: TestGetNor (0.00s)
=== RUN TestPostJsonNor
2021/10/18 18:56:49 post請求json表單
--- PASS: TestPostJsonNor (0.00s)
=== RUN TestPostFormNor
2021/10/18 18:56:49 post請求form表單
--- PASS: TestPostFormNor (0.00s)
=== RUN TestStageJSON
看完了這篇文章,相信你對“Golang如何請求fasthttp”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。