Encode JSON Response in Go

Posted by yhuang
Public (Editable by Users)
Go
Edit
package main

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

type User struct {
	Firstname string `json:"firstname"`
	Lastname  string `json:"lastname"`
	Age       int    `json:"age"`
}

func main() {
	http.HandleFunc("/encode", func(w http.ResponseWriter, r *http.Request) {
		peter := User{
			Firstname: "John",
			Lastname:  "Doe",
			Age:       25,
		}

		json.NewEncoder(w).Encode(peter)
	})

	http.ListenAndServe(":8080", nil)
}

// $ go run json.go
// $ curl -s http://localhost:8080/encode
// {"firstname":"John","lastname":"Doe","age":25}