シンプルな JSON API サーバー。
コピペ用
コード
package main
import (
"encoding/json"
"log"
"net/http"
)
type Post struct {
ID int `json:"id"`
Title string `json:"title"`
Body string `json:"body"`
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(&Post{ID: 1, Title: "hello", Body: "world"}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
log.Fatalln(http.ListenAndServe(":8080", nil))
}
確認
ブラウザから http://localhost:8080/
にアクセスする
{
id: 1,
title: "hello",
body: "world"
}
curl -i http://localhost:8080/
でアクセスする
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 40
{"id":1,"title":"hello","body":"world"}