Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does Golang request fasthttp

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

The editor will share with you how Golang requests fasthttp. I hope you will get something after reading this article. Let's discuss it together.

Basic API Demo

First of all, share the basic usage encapsulation:

PS: this is an exercise version, so there are not many comments.

Package ftimport ("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 ("request failed:", err.Error () return nil, err} return resp, err} func FastPostForm (url string) Args map [string] interface {}) ([] byte, error) {/ / fill in the form Similar to 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 ("request failed:", err.Error () return nil, err} return resp, nil} func FastPostJson (url string, args mapstring] interface {}) ([] byte Error) {req: = & fasthttp.Request {} req.SetRequestURI (url) marshal, _: = json.Marshal (args) req.SetBody (marshal) / / default is application/x-www-form-urlencoded, but it doesn't matter that req.Header.SetContentType ("application/json") req.Header.SetMethod ("POST") resp: = & fasthttp.Response {} if err: = fasthttp.Do (req, resp) Err! = nil {fmt.Println ("request failed:", err.Error ()) return nil, err} return resp.Body (), nil}

There are two main points to note:

FastGet and FastPostForm use the default way to obtain requests provided by fasthttp, and FastPostJson uses custom requests and get responses.

With regard to the req.Header.SetContentType method in the request header, it doesn't matter, the server can parse it.

High performance API demonstration

Here's how to create requests and get responses using higher-performance (object pool-based) API:

Package taskimport ("crypto/tls"encoding/json"fmt"github.com/valyala/fasthttp"log"time") var FastClient fasthttp.Client = fastClient () / / FastGet gets the GET request object without recycling / / @ Description:// @ param url// @ param args// @ return * fasthttp.Requestfunc FastGet (url string Args mapping [string] interface {}) * fasthttp.Request {req: = fasthttp.AcquireRequest () req.Header.SetMethod ("GET") values: = ToValues (args) req.SetRequestURI (url + "?" + values) return req} / / FastPostJson POST request JSON parameter, no resource recovery / / @ Description:// @ param url// @ param args// @ return * fasthttp.Requestfunc FastPostJson (url string Args map [string] interface {}) * fasthttp.Request {req: = fasthttp.AcquireRequest () / / default is 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 request form to pass parameters There is no resource recovery / / @ Description:// @ param url// @ param args// @ return * fasthttp.Requestfunc FastPostForm (url string, args map [string] interface {}) * fasthttp.Request {req: = fasthttp.AcquireRequest () / / default is 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 get the response and ensure resource recovery / / @ Description:// @ param request// @ return [] byte// @ return errorfunc 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 ("response error") return nil, err} return response.Body (), nil} / / DoGet send a GET request to get the response / / @ Description:// @ param url// @ param args// @ return [] byte// @ return errorfunc DoGet (url string, args mapping [string] interface {}) ([] byte) Error) {req: = fasthttp.AcquireRequest () defer fasthttp.ReleaseRequest (req) / / need to release resources req.Header.SetMethod ("GET") values: = ToValues (args) req.SetRequestURI (url + "?" + values) resp: = fasthttp.AcquireResponse () defer fasthttp.ReleaseResponse (resp) / / need to release resources if err: = FastClient.Do (req, resp) Err! = nil {fmt.Println ("request failed:", err.Error ()) return nil, err} return resp.Body (), nil} / / fastClient get fast client / / @ Description:// @ return fasthttp.Clientfunc 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,}} test service

Using the same moco_FunTester test framework, the script is as follows:

Package com.mocofun.moco.mainimport com.funtester.utils.ArgsUtilimport com.mocofun.moco.MocoServerimport org.apache.tools.ant.taskdefs.condition.Andclass Share extends MocoServer {static void main (String [] args) {def util = new ArgsUtil (args) / / def server = getServerNoLog (util.getIntOrdefault (0mem12345)) def server = getServer (util.getIntOrdefault (0Mae 12345)) server.get (both (urlStartsWith ("/ test")) ExistArgs ("code")) .response ("get request") server.post (both (urlStartsWith ("/ test"), existForm ("fun")) .response ("post request form form") server.post (both (urlStartsWith ("/ test"), existParams ("fun")) .response ("post request json form") server.get (urlStartsWith ("/ qps")) .response (textRes ("congratulations on arriving 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 unit test

When I wrote the Golang single test for the first time, I didn't get used to it. It took me a long time to get through.

Package testimport ("funtester/ft"funtester/task"log"testing") const url = "http://localhost:12345/test"func args () 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 request" {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 request json form" {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 request form 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 request" {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 request json form" {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 request form form" {t.Fail ()}} Test report

Use the built-in console output content:

= RUN TestGet

18:56:49 on 2021-10-18 get request

-PASS: TestGet (0.01s)

= RUN TestPostJson

18:56:49 on 2021-10-18 post requested an json form

-PASS: TestPostJson (0.00s)

= RUN TestPostForm

18:56:49 on 2021-10-18 post requested an form form

-PASS: TestPostForm (0.00s)

= RUN TestGetNor

18:56:49 on 2021-10-18 get request

-PASS: TestGetNor (0.00s)

= RUN TestPostJsonNor

18:56:49 on 2021-10-18 post requested an json form

-PASS: TestPostJsonNor (0.00s)

= RUN TestPostFormNor

18:56:49 on 2021-10-18 post requested an form form

-PASS: TestPostFormNor (0.00s)

= RUN TestStageJSON

After reading this article, I believe you have a certain understanding of "how Golang requests fasthttp". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report