サンプルコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
package main import ( "encoding/json" "fmt" "net/http" ) // 構造を宣言 type User struct { Name string `json:"name"` Age int `json:"age"` } func main() { // POST http.HandleFunc("/post", func(w http.ResponseWriter, r *http.Request) { var user User json.NewDecoder(r.Body).Decode(&user) fmt.Fprintf(w, "%s is %d years old!", user.Name, user.Age) }) // GET http.HandleFunc("/get", func(w http.ResponseWriter, r *http.Request) { yuta := User{ Name: "yuta", Age: 666, } json.NewEncoder(w).Encode(yuta) }) http.ListenAndServe(":8080", nil) } |
PostとGet
1 2 3 4 5 6 7 8 |
yuta:~ $ curl -s http://localhost:8080/get {"name":"yuta","age":666} yuta:~ $ yuta:~ $ yuta:~ $ curl -s -XPOST -d'{"name":"tadokoro","age":24}' http://localhost:8080/post tadokoro is 24 years old!yuta:~ $ yuta:~ $ yuta:~ $ |