development-ib-fork/web/07/demos/06_decode_json.go

27 lines
532 B
Go

package main
import (
"encoding/json"
"fmt"
"net/http"
)
type jsonDecodeHandler int
type User struct {
Firstname string `json:"firstname"`
Lastname string `json:"lastname"`
Age int `json:"age"`
}
func (jsonHandler jsonDecodeHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var user User
json.NewDecoder(r.Body).Decode(&user)
fmt.Fprintf(w, "%s %s is %d years old!", user.Firstname, user.Lastname, user.Age)
}
func main() {
var dec jsonDecodeHandler
http.ListenAndServe("localhost:8080", dec)
}