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
    
【励志篇】:
古之成大事掌大学问者,不惟有超世之才,亦必有坚韧不拔之志。
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号