阅读 323

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://www.cnblogs.com/tomtellyou/p/15155366.html

文章分类
代码人生
文章标签
版权声明:本站是系统测试站点,无实际运营。本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 XXXXXXo@163.com 举报,一经查实,本站将立刻删除。
相关推荐