JSON decoding in golang

huangapple go评论71阅读模式
英文:

JSON decoding in golang

问题

所以我根据这里的示例尝试了一些代码,但没有得到任何数据,也没有错误。代码如下:

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

type Credential struct {
    username string `json:"username"`
    password string `json:"password"`
}

func login(res http.ResponseWriter, req *http.Request) {
    if req.Method == "POST" {
        cred := Credential{}
        err := json.NewDecoder(req.Body).Decode(&cred)
        if err != nil {
            panic("can't decode")
        }
        fmt.Println("credentials: " + cred.username + " , " + cred.password)
    }
}

我使用以下命令进行测试:

curl -X POST -H "Accept: application/json" --data "{\"username\":\"x\",\"password\":\"y\"}" 127.0.0.1:8000/login -i

服务器打印出:

credentials:  , 

为什么 cred.username 和 cred.password 中没有任何内容?

英文:

So I tried something based on the example here in my code, and get no data, but no error either. The code is:

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

type Credential struct {
    username string `json:"username"`
    password string `json:"password"`
}

func login(res http.ResponseWriter, req *http.Request) {
    if req.Method == "POST" {
        cred := Credential{}
        err := json.NewDecoder(req.Body).Decode(&cred)
        if err != nil {
            panic("can't decode")
        }
        fmt.Println("credentials: " + cred.username + " , " + cred.password)
    }
}

I test with

> curl -X POST -H "Accept: application/json" --data "{"username":"x","password":"y"}" 127.0.0.1:8000/login -i

And the server prints out:

> credentials: ,

Why is there nothing in cred.username and cred.password?

答案1

得分: 4

Golang使用字段的首字母来声明该结构体的公有或私有性质。所以将username改为Username

英文:

golang use first character of the field to declare public or private for that struct. so change username to Username

huangapple
  • 本文由 发表于 2015年6月18日 08:47:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/30904781.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定