GOのJSONAPI

GoでJSONを返すAPIを作る

Encodeするには構造体などの型を予め作る必要がある.項目名を動的に変更したい場合は

map[]interface{}

というmapオブジェクトを使えばよい.

WriterオブジェクトをもとにEncoderを作成して,各オブジェクトをエンコードする.

package main

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

type Hoge{
  foo string `json:foo`
  bar int64  `json:baba`
}

func main(){
  http.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request){
    hoge := Hoge{
      foo: "Foo".
      bar: 111,
    }
    t := map[string]interface{}{
      "name": "hoge",
      "foo":  334,
    }
    t["hoge"] = "fuga"

   //ResponseWriterに書き込むEnocderを作成
    encoder := json.NewEncoder(w)
    //Encoder(Writer)にオブジェクトをjsonとしてエンコード
    encoder.Encode(hoge)
    encoder.Encode(t)
  }
  http.ListenAndServe(":8080", nil)
}

APIがNameとAgeをもつオブジェクトを返すものだとしたらHTML側ではこんな感じに,APIコールする.

XMLHttpRequestよりfetchの方がいいかもしれない.javascriptはよく分からないので,このwebサイトを参考にしていた.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div id="hoge">
        <table>
            <thead>
                <tr>
                    <th>Name</th>
                    <th>Age</th>
                </tr>
            </thead>
            <tbody id="t-body">
            </tbody>
        </table>
    </div>
    <script type="text/javascript">
        let xhr = new XMLHttpRequest();
        let url = "http://localhost:8080/api"
        xhr.open("GET", url, async=true)
        xhr.send()
        xhr.onload = () => {
            console.log(xhr.status)
            console.log(xhr.response)
            json = JSON.parse(xhr.response)
            console.log(json)
            row = document.createElement("tr")
            nm = document.createElement("td")
            nm.innerText = json.Name
            age = document.createElement("td") 
            age.innerText = json.Age
            row.append(nm, age)
            tbody = document.getElementById("t-body")
            tbody.append(row)
        }
    </script>
</body>
</html>