LoginSignup
18
16

More than 5 years have passed since last update.

GoのJSON API ServerでゆるふわJSON responseを返す方法

Last updated at Posted at 2016-10-25

ブログのコピペです(https://t-hiroyoshi.github.io/go-yuru-json)

最近GoをAPI Gateway(Aggregator)としている環境で開発を行なっているのですが、呼び出し先のServiceの実装が終わっていなくてもClientでとりあえずJSONのresponseが欲しいという状況がありました。

JSONのUnmarshalについてはgolangはゆるふわにJSONを扱えまぁす!という記事が有ったのですが、ゆるふわMarshalについては情報がありませんでした。

ですが考えてみればjson.Marshal()すると[]byte型になるのでそれを初めから作ってあげればよかったです。
まあもちろんこれではGoの良いところを捨てているようなものですが、開発中のとりあえずのレスポンスには手軽で良いと思いました。

package main

import (
    "fmt"
    "net/http"
)

func jsonResponse(rw http.ResponseWriter, req *http.Request) {
    response := []byte(`
        {
          "status": "success",
          "user":
            {
              "id": "2d7b8fe1-1e63-4c3b-83b9-46274554e822",
              "name": "t-hiroyoshi",
              "birthday": "1993-09-06T11:22:33.496Z"
            }
        }
    `)

    defer func() {
        rw.Header().Set("Content-Type", "application/json")
        fmt.Fprint(rw, string(response))
    }()
}

func main() {
    http.HandleFunc("/json", jsonResponse)
    http.ListenAndServe(":8080", nil)
}
18
16
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
18
16