【Golang】GoFrame 框架处理json参数以常规方式接收

Go语言 小铁匠 2020-05-04

在 GoFrame 框架中可以使用 r.Request.Get() 接收参数,但application/json参数不能以这种方式接收。
可以使用 r.Request.GetRaw() 接收,但返回值是[]byte类型需要进一步转化很不方便。
于是我便想写一个公共处理让application/json参数可以像接收form-data参数一样接收。

在util包下写一个公共方法 request.go

package util

import (
    "encoding/json"
    "github.com/gogf/gf/g/net/ghttp"
    "github.com/gogf/gf/g/util/gconv"
    "io/ioutil"
    "strings"
)

// 设置请求
func Request(r *ghttp.Request) {
    contentType := r.Request.Header.Get("Content-type")
    if strings.Index(contentType, "application/json") > -1 {
        body,_ := ioutil.ReadAll(r.Body)
        var queryMap map[string]interface{}
        err := json.Unmarshal(body, &queryMap)
        if err == nil {
            method := r.Request.Method

            var value string
            for key := range queryMap {
                value = gconv.String(queryMap[key])
                if method == "POST" {
                    r.AddPost(key, value)
                } else {
                    r.AddQuery(key, value)
                }
            }
        }
    }
}

然后在路由中设置这个方法为前置操作:

package router

import (
    "github.com/gogf/gf/g"
    "github.com/gogf/gf/g/net/ghttp"
    "gomod/library/util"
)

func init() {
    s := g.Server()
    s.Group("/v1").Bind([]ghttp.GroupItem{
        {"ALL", "*", HookHandler, ghttp.HOOK_BEFORE_SERVE},
    })
}

func HookHandler(r *ghttp.Request) {
    util.Request(r)
}

然后就可以用r.Request.Get()接收了。

------ 本文结束 感谢阅读 ------