一、golang中处理http响应数据解码,一般有两种方式:

1:json.Unmarshal进行解码
func HandleUse(w http.ResponseWriter, r *http.Request) {
    var u Use //此处的Use是一个结构体
    data, err := ioutil.ReadAll(r.Body)//此处的r是http请求得到的json格式数据-->然后转化为[]byte格式数据.
    if err != nil {
        w.WriteHeader(http.StatusBadRequest)
        return
    }
    if err := json.Unmarshal(data, &u); err != nil { //经过这一步将json解码赋值给结构体,由json转化为结构体数据
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    w.WriteHeader(http.StatusOK)
    fmt.Fprintf(w, "姓名:%s,年龄:%d", u.Name, u.Age)

}
2. json.NewDecoder解码
func HandleUse(w http.ResponseWriter, r *http.Request) {
    var u Use
    if err := json.NewDecoder(r.Body).Decode(&u); err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
    w.WriteHeader(http.StatusOK)
    fmt.Fprintf(w, "姓名:%s,年龄:%d", u.Name, u.Age)

}

二、区别:

1、json.NewDecoder是从一个里面直接进行解码,代码精干;
2、json.Unmarshal是从已存在与内存中的json进行解码;
3、相对于解码,json.NewEncoder进行大JSON的编码比json.marshal性能高,因为内部使用pool。

三、场景应用:

1、json.NewDecoder用于http连接与socket连接的读取与写入,或者文件读取;
2、json.Unmarshal用于直接是byte的输入。

Logo

AtomGit 是由开放原子开源基金会联合 CSDN 等生态伙伴共同推出的新一代开源与人工智能协作平台。平台坚持“开放、中立、公益”的理念,把代码托管、模型共享、数据集托管、智能体开发体验和算力服务整合在一起,为开发者提供从开发、训练到部署的一站式体验。

更多推荐