JSON

This example will show how to encode and decode JSON data using the encoding/json package.

  1. // json.go
  2. package main
  3. import (
  4. "encoding/json"
  5. "fmt"
  6. "net/http"
  7. )
  8. type User struct {
  9. Firstname string `json:"firstname"`
  10. Lastname string `json:"lastname"`
  11. Age int `json:"age"`
  12. }
  13. func main() {
  14. http.HandleFunc("/decode", func(w http.ResponseWriter, r *http.Request) {
  15. var user User
  16. json.NewDecoder(r.Body).Decode(&user)
  17. fmt.Fprintf(w, "%s %s is %d years old!", user.Firstname, user.Lastname, user.Age)
  18. })
  19. http.HandleFunc("/encode", func(w http.ResponseWriter, r *http.Request) {
  20. peter := User{
  21. Firstname: "John",
  22. Lastname: "Doe",
  23. Age: 25,
  24. }
  25. json.NewEncoder(w).Encode(peter)
  26. })
  27. http.ListenAndServe(":8080", nil)
  28. }
  1. $ go run json.go
  2. $ curl -s -XPOST -d'{"firstname":"Donald","lastname":"Trump","age":70}' http://localhost:8080/decode
  3. Donald Trump is 70 years old!
  4. $ curl -s http://localhost:8080/encode
  5. {"firstname":"John","lastname":"Doe","age":25}