0

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?

Community
  • 1
  • 1
Yusuf X
  • 14,513
  • 5
  • 35
  • 47
  • 1
    Probably not related, but it's always a good idea to supply content type in the header as well with `-H "Content-Type: application/json"`. – kichik Jun 18 '15 at 00:49

1 Answers1

4

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

Jiang YD
  • 3,205
  • 1
  • 14
  • 20