简体   繁体   English

如何在 GET 请求中发送结构

[英]How do you send a struct in a GET request

If I create a struct, how do I send it with a HTTP GET request to a web server endpoint?如果我创建了一个结构体,如何将它与 HTTP GET 请求一起发送到 Web 服务器端点?

package main

import (
    "encoding/json"
    "net/http"
)

type Payload struct {
    Endpoint string `json:"endpoint"`
    Data map[string]interface{} `json:"data"`
}

/*
eg.
{"endpoint":"some-service", "data": {"userID": "abc123"}}
*/

func main() {

    http.HandleFunc("/service", func(w http.ResponseWriter, r *http.Request) {

        decoder := json.NewDecoder(r.Body)
        var p Payload
        err := decoder.Decode(&p)
        if err != nil {
            panic(err)
        }

        // How to attach 'p' ?
        resp, err := http.Get("www.example.com/" + p.Endpoint) // Add "data": p.Data
        if err != nil {
            log.Fatal(err)
        }
        defer resp.Body.Close()

        // handle response here

    })

    http.ListenAndServe(":8080", nil)

}

The endpoint receiving this data would ideally interpret it as JSON.理想情况下,接收此数据的端点会将其解释为 JSON。

HTTP GET requests do not allow a request body. HTTP GET请求不允许请求正文。

If you must do it with a GET , basically you have 2 options: add the data as a query parameter, or send it in an HTTP Header field.如果你必须用GET来做,基本上你有 2 个选项:将数据添加为查询参数,或将其发送到 HTTP 标头字段中。

Note that both the URL and header fields have length limits, so if you want to "attach" a long JSON text, it might fail.请注意,URL 和标头字段都有长度限制,因此如果您想“附加”很长的 JSON 文本,它可能会失败。 To send arbitrary data, you should use another method, eg POST .要发送任意数据,您应该使用另一种方法,例如POST

Example adding it as a query param:将其添加为查询参数的示例:

u, err := url.Parse("http://www.example.com")
if err != nil {
    panic(err)
}

params := url.Values{}
params.Add("data", `{"a":1,"b":"c"}`)
u.RawQuery = params.Encode()

// use u.String() as the request URL

Example sending it in a Header field:在 Header 字段中发送它的示例:

req, err := http.NewRequest("GET", "http://example.com", nil)
// ...
req.Header.Add("X-Data", `{"a":1,"b":"c"}`)
resp, err := client.Do(req)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM