在Go Lang POST请求中创建JSON负载? [英] Create a json payload in Go Lang POST request?

查看:58
本文介绍了在Go Lang POST请求中创建JSON负载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

request, err := http.NewRequest("POST", url,bytes.NewBuffer(**myJsonPayload**))

我是Go语言的新手,并尝试使用动态" myJsonPayload "发出发布请求,该请求将针对不同的请求进行更改.

I am new in Go and trying to make post request with dynamic 'myJsonPayload', which will be changing for different request.

推荐答案

使用 Marshal(位于Go的标准库的 encoding/json 中)中,以将数据编码为JSON.

Use Marshal in the encoding/json package of Go's standard library to encode your data as JSON.

签名:

func Marshal(v interface{}) ([]byte, error)

来自包文档的示例,其中输入数据恰好是具有int,string和string slice字段类型的结构类型:

Example from package docs, where input data happens to be a struct type with int, string, and string slice field types:

type ColorGroup struct {
    ID     int
    Name   string
    Colors []string
}
group := ColorGroup{
    ID:     1,
    Name:   "Reds",
    Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
}
b, err := json.Marshal(group)

这篇关于在Go Lang POST请求中创建JSON负载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆