サンプルコード

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

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:~ $

 

 

 

<スポンサーリンク>

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

*

日本語が含まれない投稿は無視されますのでご注意ください。(スパム対策)