Goでnet/httpな簡単なJSON API

朝活#2

code

localhost:8080/jsonに向けてJSONをPOSTするとJSONが返ってきます。

package main

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

type Input struct {
    In string
}

type Output struct {
    Out string
}

func jsonHandleFunc(rw http.ResponseWriter, req *http.Request) {
    output := Output{"返ってくる"}
    defer func() {
        outjson, e := json.Marshal(output)
        if e != nil {
            fmt.Println(e)
        }
        rw.Header().Set("Content-Type", "application/json")
        fmt.Fprint(rw, string(outjson))
    }()
    if req.Method != "POST" {
        output.Out = "Not post..."
        return
    }
    body, e := ioutil.ReadAll(req.Body)
    if e != nil {
        output.Out = e.Error()
        fmt.Println(e.Error())
        return
    }
    input := Input{}
    e = json.Unmarshal(body, &input)
    if e != nil {
        output.Out = e.Error()
        fmt.Println(e.Error())
        return
    }
    fmt.Printf("%#v\n", input)
}

func main() {
    fs := http.FileServer(http.Dir("static"))
    http.Handle("/", fs)
    http.HandleFunc("/json", jsonHandleFunc)
    http.ListenAndServe(":8080", nil)
}

動作している様子

POSTしている様子

$ curl -v -H "Accept: application/json" -H "Content-type: application/json" -X POST -d '{"In": "イィイィィィンッ"}' http://localhost:8080/json
# curlの表示(長いので省略)
{"Out":"返ってくる"}%

Serverの様子

$ go run server.go
main.Input{In:"イィイィィィンッ"}

staticディレクトリを掘ると、そこのファイルがルートで見れるようにしているので、そこからJSON APIに向けてPOSTして良しなにする感じのSPAを作る予定。

まとめ

調べるのと理解に時間がかかった(2時間くらい)、発明された車輪を使用するほうがいいかもしれないと何度も思った。

参考資料

Show comments

Adsense

Share

  • このエントリーをはてなブックマークに追加

About

どこにでもいる平凡なプログラムを書く人間のログ。

Recently

Tags

Pages

-->