Golang如何解析post请求中的json字符串|Go主题月

878 阅读2分钟

目录

问题

解决

问题

使用Golang开发服务器,最常用的使用场景之一就是处理各种http请求。那么我们如何使用Golang解析Post请求中的Json字符串呢?今天我们就来通过一个实例了解一下。

解决

首先,我们需要定义好对应的消息结构,也就是前端请求服务器的API接口。定义接口的话推荐使用工具YAPI编写,支持预览、编辑、导出,非常方便。自己平时用的比较多。

hellosean1025.github.io/yapi/docume…

比如:

type recordConfig struct {

    StreamPath string `json:"streamPath"`

    Append bool `json:"append"`

    Protocol string `json:"protocol"`

    Url string `json:"url"`

}

接口完成后,接下来我们开始处理http的请求。对于http请求,我们知道post请求的参数都是放在body中,我们需要先获取body,再解析其中的参数。

通过代码,我们来看一下如何读取对应请求的body信息。

代码如下:

body, err := ioutil.ReadAll(r.Body)

defer r.Body.Close()

if err != nil {

    return

}

最后,解析Json字符串为Json对象。

注意:这里有两种方式,都是非常方便的,具体方式请自选。

但是,这两种方法都需要首先入库json库,代码:

import (   
    "encoding/json"
)

方法一、利用Unmarshal()方法

Unmarshal是json库的一个内部方法,它的第一个参数是json字符串,第二个参数是接受json解析的数据结构。 注意:第二个参数必须是指针,否则无法接收解析的数据。

Unmarshal方法的源码:

// When unmarshaling quoted strings, invalid UTF-8 or// invalid UTF-16 surrogate pairs are not treated as an error.// Instead, they are replaced by the Unicode replacement// character U+FFFD.// func Unmarshal(data []byte, v interface{}) error {    // Check for well-formedness.    // Avoids filling out half a data structure    // before discovering a JSON syntax error.    var d decodeState    err := checkValid(data, &d.scan)    if err != nil {        return err    }    d.init(data)    return d.unmarshal(v)}

通过源码我们知道,Unmarshal方法处理的参数1是一个字节数组。这一点非常好,因为 body 中就是字节数组的形式,所以我们可以直接使用。

最后,我们给出对应的代码实例:

var conf recordConfig

err := json.Unmarshal(body, &conf)

接下来,我们看方法二。

方法二、利用NewDecoder组合方法

首先,我们看一下源码:

// NewDecoder returns a new decoder that reads from r.//// The decoder introduces its own buffering and may// read data from r beyond the JSON values requested.func NewDecoder(r io.Reader) *Decoder {    return &Decoder{r: r}}

我们知道,NewDecoder方法只需要一个参数,类型是io.Reader,而 r.Body 的类型正好符合,所以我们不用像方法一那样,需要用下面的方法进行转换。

ioutil.ReadAll(r.Body)

最后,给出对应的代码实例:

var conf recordConfig

err := json.NewDecoder(r.Body).Decode(&conf)

至此,我们就可以使用 conf.StreamPath 获取流路径信息了。然后,开始服务器的后续工作。