简体   繁体   中英

Decoding JSON from POST request fails in Go

I send a POST request to my Go application with JSON data like below:

var test = {text: "Lorem ipsum dolor sit amet"};

$.ajax({
  url: "/api/test/add",
  type: "POST",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  data: JSON.stringify(test),
  success: function(data) {
    // ...
  },
  error: function(xhr, status, err) {
    // ...
  }
});

In my Go application I have the following code (using vestigo ):

type Test struct {
  id   int
  text string
}

func apiAddTestHandler(w http.ResponseWriter, r *http.Request) {
  r_body, err := ioutil.ReadAll(r.Body)
  if err != nil {
    panic(err)
  }

  // Here looks like everything is ok because I get
  // {"text": "Lorem ipsum dolor sit amet"} if I try
  // to convert r_body to string (string(r_body)).

  var test Test
  err = json.Unmarshal(r_body, &test)
  if err != nil {
    panic(err)
  }

  // Process test struct below, but here I get
  // {id:0 text:} if I try to use or print the value
  // of test (fmt.Printf("%+v\n", test)).
}

func main() {
  router := vestigo.NewRouter()
  router.Post("/api/test/add", apiAddTestHandler)

  err := http.ListenAndServe(":3000", router)
  if err != nil {
    log.Fatal("ListenAndServe: ", err)
  }
}

The problem is, that in apiAddTestHandler() I cannot "populate" the test struct with the decoded JSON data. A little bit more info in the comments. I also tried the below snippet with no luck:

decoder := json.NewDecoder(r.Body)
var test Test
err := decoder.Decode(&test)
if err != nil {
  panic(err)
}

What is the problem?

From the Unmarshal documentation (emphasis is mine):

To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. Unmarshal will only set exported fields of the struct .

You need to change the field definition in your struct:

type Test struct {
  ID   int
  Text string
}

Note I used ID instead of Id per Golang naming conventions .

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