登录
首页 >  Golang >  Go问答

在使用curl调用时,json.Unmarshal不会填充结构

来源:stackoverflow

时间:2024-03-28 10:15:23 102浏览 收藏

积累知识,胜过积蓄金银!毕竟在Golang开发的过程中,会遇到各种各样的问题,往往都是一些细节知识点还没有掌握好而导致的,因此基础知识点的积累是很重要的。下面本文《在使用curl调用时,json.Unmarshal不会填充结构》,就带大家讲解一下知识点,若是你对本文感兴趣,或者是想搞懂其中某个知识点,就请你继续往下看吧~

问题内容

我正在尝试填充结构并执行一些进一步的操作,结构中的字段已导出,但当我执行卷曲时该值并未填充。

package main

import (
    "encoding/json"
    "io/ioutil"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

type y struct {
    name      string   `json:"name"`
    eventtype []string `json:"eventtype"`
}

func main() {
    router := mux.newrouter()
    router.handlefunc("/config/export/eventtypes", eventtypes).methods("get")
    router.handlefunc("/config/export/ia/outputs", createeventlist).methods("post")
    http.listenandserve(":8000", router)
}

func eventtypes(w http.responsewriter, r *http.request) {
    w.header().set("content-type", "application/json")

    var resp []map[string]string
    x := make(map[string]string)
    x["name"] = "http"
    x["description"] = "http"
    resp = append(resp, x)
    x1 := make(map[string]string)
    x1["name"] = "krb"
    x1["description"] = "http"
    resp = append(resp, x1)
    x2 := make(map[string]string)
    x2["name"] = "fileinfo"
    x2["description"] = "http"
    resp = append(resp, x2)

    json.newencoder(w).encode(resp)
}

func createeventlist(w http.responsewriter, r *http.request) {
    var s y
    x, _ := ioutil.readall(r.body)
    log.printf("%v", string(x))
    json.unmarshal([]byte(x), &s)
    log.printf("%+v", s)

}

我正在使用 curl -h "content-type: application/json" -x post http://localhost:8000/config/export/ia/outputs -d'{"name":"test", 对此进行测试"eventtype":"["http","dmtp"]"}' 我的输出是 { []} 但当我尝试使用 python 代码时也是同样的事情

myobj = {"name":"test","eventType":test}

y= requests.post("http://localhost:8000/config/export/ia/outputs",json=myobj)

打印 {name:test eventtype:[http krb fileinfo]}


解决方案


删除curl请求中数组的引号

终于介绍完啦!小伙伴们,这篇关于《在使用curl调用时,json.Unmarshal不会填充结构》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>