golang FastHttp 使用


golang FastHttp 使用

1. 路由處理

package main

import (
    "fmt"
    "github.com/buaazp/fasthttprouter"
    "github.com/valyala/fasthttp"
    "log"
)

func main() {

    // 創建路由
    router := fasthttprouter.New()

    // 不同的路由執行不同的處理函數
    router.GET("/", Index)

    router.GET("/hello", Hello)

    // post方法
    router.POST("/post", TestPost)

    // 啟動web服務器,監聽 0.0.0.0:12345
    log.Fatal(fasthttp.ListenAndServe(":12345", router.Handler))
}

// index 頁
func Index(ctx *fasthttp.RequestCtx) {
    fmt.Fprint(ctx, "Welcome")
    values := ctx.QueryArgs() // 使用 ctx.QueryArgs() 方法 
    fmt.Fprint(ctx,  string(values.Peek("abc"))) // 不加string返回的byte數組 
    fmt.Fprint(ctx,  string(ctx.FormValue("abc"))) // 獲取表單數據
}


// 獲取post的請求json數據
func TestPost(ctx *fasthttp.RequestCtx) {
 
    postBody := ctx.PostBody() // 這兩行可以獲取PostBody數據,文件上傳也有用
    fmt.Fprint(ctx, string(postBody))
 
    fmt.Fprint(ctx, string(ctx.FormValue("abc"))) // 獲取表單數據
}

2. Get請求

package main

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

func main() {
    url := `http://baidu.com/get`

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

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

3. Post請求

(1.) 填充表單形式
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))
}
(2.)json請求
func main() {
    url := `http://xxx/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))
}
(3.)性能提升
func main() {
    url := `http://xxx/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))
}

參考鏈接

https://github.com/DavidCai1993/my-blog/issues/35

https://www.codercto.com/a/53034.html

https://juejin.cn/post/6844903761832476686


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM