go语言fasthttp使用实例

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/m0_38004619/article/details/102711382

一、服务搭建和接收参数实例

package main

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

// index 页
func Index(ctx *fasthttp.RequestCtx) {
    ctx.Request.Header.Peek("userid")//获取header头参数
    fmt.Fprint(ctx, "Welcome")
}


// 简单路由页
func Hello(ctx *fasthttp.RequestCtx) {
    name:= ctx.UserValue("name").(string) //获取路由参数name
    fmt.Fprintf(ctx, "hello")
}

// 获取GET请求json数据
func TestGet(ctx *fasthttp.RequestCtx) {
    
    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"))) // 获取表单数据
}

func main() {

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

    // 不同的路由执行不同的处理函数
    router.GET("/", Index)

    router.GET("/hello/:name", Hello)

    router.GET("/get", TestGet)

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

    // 启动web服务器,监听 0.0.0.0:80
    log.Fatal(fasthttp.ListenAndServe(":08", router.Handler))
}

二、Post和Get请求实例

package main

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

func main() {

	req := &fasthttp.Request{} //相当于获取一个对象

	req.SetRequestURI("www.baidu.com")//设置请求的url

	bytes, err := json.Marshal(data)//data是请求数据

	if err != nil {
		return nil, err
	}

	req.SetBody(bytes)//存储转换好的数据

	req.Header.SetContentType("application/json")//设置header头信息

	req.Header.SetMethod(method)//设置请求方法

	resp := &fasthttp.Response{}//相应结果的对象

	client := &fasthttp.Client{}//发起请求的对象

	if err := client.Do(req, resp); err != nil {
		return nil, err
	}

	var param model.Data //定义好的结构体用来存放相应数据

	err = json.Unmarshal(resp.Body(), &param)

	if err != nil {
		return nil, err
    }

	return param, nil

}

猜你喜欢

转载自blog.csdn.net/m0_38004619/article/details/102711382
今日推荐