程序开发 · 2024年1月4日

在 Go 中使用 http.Request 将 URL 参数转换为 JSON

当前位置: > > > > 在 Go 中使用 http.Request 将 URL 参数转换为 JSON

来源:stackoverflow
2024-04-19 17:36:34
0浏览
收藏

今天给大家带来了《在 Go 中使用 http.Request 将 URL 参数转换为 JSON》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~

问题内容

我正在验证请求中发出的参数,但与以 json 发出请求时不同,我无法轻松地将查询参数转换为其对应的结构体。使用以下内容:

https://thedevsaddam.medium.com/an-easy-way-to-validate-go-request-c15182fd11b1

type itemsrequest struct {
    item         string `json:"item"`
}
func ValidateItemRequest(r *http.Request, w http.ResponseWriter) map[string]interface{} {
    var itemRequest ItemsRequest
    rules := govalidator.MapData{
        "item":        []string{"numeric"},
    }

    opts := govalidator.Options{
        Request:         r,    
        Rules:           rules,
        Data:            &itemRequest ,
        RequiredDefault: true,
    }
    v := govalidator.New(opts)
    
    e := v.Validate()
    // access itemsRequest.item

}

如果我使用 e.validatejson() 并通过正文传递数据,则此方法有效

如果我使用 e.validate() 并通过 url 参数传递数据,则这不起作用。

我认为结构中的 json 标记是问题所在,但删除它会产生相同的结果。我不认为 validate() 应该填充该结构,但是我应该如何传递 url 的值?

我知道我可以使用 r.url.query().get() 手动提取每个值,但在我刚刚验证了我想要的所有内容后,这似乎非常多余。

正确答案

可以为您完成繁重的工作,将 url.values 转换为 struct 并进行一些架构验证。

它支持类似于 json 的结构字段标签,并且与 json 兼容,并且还可以与表单数据或多部分表单数据一起使用。

package main

import(
   "github.com/gorilla/schema"
   "net/url"
   "fmt"
)


type Person struct {
    Name  string
    Phone string
}

func main() {
    var decoder = schema.NewDecoder()
    u, err := url.Parse("http://localhost/?name=daniel&phone=612-555-4321")
    if err != nil { panic(err) }
    var person Person
    err = decoder.Decode(&person, u.Query())
    if err != nil {
        // Handle error
    }
    fmt.Printf("%+v\n", person)
}

好了,本文到此结束,带大家了解了《在 Go 中使用 http.Request 将 URL 参数转换为 JSON》,希望本文对你有所帮助!关注公众号,给大家分享更多Golang知识!