LoginSignup
2
0

More than 5 years have passed since last update.

Go Web Examplesの和訳(JSON)

Last updated at Posted at 2018-12-09

Go勉強会 Webアプリケーション編 #3 でやろうと思っている Go Web Examples: JSON の和訳です。これもほとんど解説文がないですけどねー

JSON

この例では encoding/json パッケージを使って JSON データをエンコードとデコードする方法を示します。

// json.go
package main

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

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

func main() {
    http.HandleFunc("/decode", func(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)
    })

    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 -XPOST -d'{"firstname":"Donald","lastname":"Trump","age":70}' http://localhost:8080/decode
Donald Trump is 70 years old!

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

補足

Go は標準ライブラリの encoding/json パッケージで JSON をサポートしています。JSON のオブジェクトは Go のマップと構造体にエンコード/デコードすることができます。JSON オブジェクトと Go の構造体のメンバの対応は構造体のフィールドタグ(json:"firstname" 等)によって指定します。フィールドタグは名前の他、JSON にエンコードする際の型、省略可能かどうか等も指定できます。

参照

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0