golang高性能的http请求 fasthttp

fasthttp 据说是目前golang性能最好的http库,相对于自带的net/http,性能说是有10倍的提升,具体介绍可以看看官方介绍: valyala/fasthttp

 

1,首先安装fasthttp

go get -u github.com/valyala/fasthttp

 

2,简单的一个get请求

package main

import (
    "github.com/valyala/fasthttp"
)

func main() {
    url := `http://httpbin.org/get`

    status, resp, err := fasthttp.Get(nil, url)
    if err != nil {
        fmt.Println("请求失败:", err.Error())
        return
    }

    if status != fasthttp.StatusOK {
        fmt.Println("请求没有成功:", status)
        return
    }

    fmt.Println(string(resp))
}

 

2,简单的Post请求

func main() {
    url := `http://httpbin.org/post?key=123`
    
    // 填充表单,类似于net/url
    args := &fasthttp.Args{}
    args.Add("name", "test")
    args.Add("age", "18")

    status, resp, err := fasthttp.Post(nil, url, args)
    if err != nil {
        fmt.Println("请求失败:", err.Error())
        return
    }

    if status != fasthttp.StatusOK {
        fmt.Println("请求没有成功:", status)
        return
    }

    fmt.Println(string(resp))
}

 

比如有些API服务需要我们提供json body或者xml body也就是,Content-Type是application/json、application/xml或者其他类型

func main() {
    url := `http://httpbin.org/post?key=123`
    
    req := &fasthttp.Request{}
    req.SetRequestURI(url)
    
    requestBody := []byte(`{"request":"test"}`)
    req.SetBody(requestBody)

    // 默认是application/x-www-form-urlencoded
    req.Header.SetContentType("application/json")
    req.Header.SetMethod("POST")

    resp := &fasthttp.Response{}

    client := &fasthttp.Client{}
    if err := client.Do(req, resp);err != nil {
        fmt.Println("请求失败:", err.Error())
        return
    }

    b := resp.Body()

    fmt.Println("result:\r\n", string(b))
}

 

翻阅文档发现了他提供了几个方法:AcquireRequest()AcquireResponse(),而且也推荐了在有性能要求的代码中,通过 AcquireRequest 和 AcquireResponse 来获取 req 和 resp。

func main() {
    url := `http://httpbin.org/post?key=123`

    req := fasthttp.AcquireRequest()
    defer fasthttp.ReleaseRequest(req) // 用完需要释放资源
    
    // 默认是application/x-www-form-urlencoded
    req.Header.SetContentType("application/json")
    req.Header.SetMethod("POST")
    
    req.SetRequestURI(url)
    
    requestBody := []byte(`{"request":"test"}`)
    req.SetBody(requestBody)

    resp := fasthttp.AcquireResponse()
    defer fasthttp.ReleaseResponse(resp) // 用完需要释放资源

    if err := fasthttp.Do(req, resp); err != nil {
        fmt.Println("请求失败:", err.Error())
        return
    }

    b := resp.Body()

    fmt.Println("result:\r\n", string(b))
}

 

posted @ 2021-09-15 08:54  pebblecome  阅读(991)  评论(0编辑  收藏  举报