jsonデータをhttpで表示する

Golangjsonデータをhttpで表示する

json.NewEncoder を使う.ファイルに書き込むときと同じようにio.Writer interfaceをもつhttp.ResponseWriterを引数にする.

package main

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

func handler(w http.ResponseWriter, r *http.Request) {
    encoder := json.NewEncoder(w)
    encoder.SetIndent("", " ")
    encoder.Encode(map[string]string{
        "golang": "great language",
        "python": "great community",
    })
        // headerを標準出力にだす
    r.Header.Write(os.Stdout)
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)

}