zoukankan      html  css  js  c++  java
  • 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:
    ", 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:
    ", string(b))
    }
    

    参考链接

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

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

    https://juejin.cn/post/6844903761832476686

    【励志篇】: 古之成大事掌大学问者,不惟有超世之才,亦必有坚韧不拔之志。
  • 相关阅读:
    正敲着代码,鼠标坏了!
    DB2 OLAP函数的使用(转)
    修剪矩形
    classpath和环境变量设置(转)
    MyEclipse断点调试JavaScript浅析(转)
    Onunload和onbeforeunload方法的异同
    db2中的coalesce函数(转)
    db2:根据TABLEID找table
    [转]DB2行列转换
    DB2删除数据时的小技巧
  • 原文地址:https://www.cnblogs.com/tomtellyou/p/15155366.html
Copyright © 2011-2022 走看看