简体   繁体   中英

JSON decoding in golang

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM