mobile hack 楽しい生活情報を携帯しよう

コンセプト「楽しい生活情報を携帯する」


Golang Go 言語の Maritini で JSON (の値) を POST 送信して JSON を返却する

import したいので、下記を実行。

$ go get github.com/codegangsta/martini
$ go get github.com/martini-contrib/binding
$ go get github.com/martini-contrib/render

post_server.go を下記にする。

package main

import (
    "net/http"

    "github.com/codegangsta/martini"
    "github.com/martini-contrib/binding"
    "github.com/martini-contrib/render"
)

type Post struct {
    Key string `json:"key" binding:"required"`
    Value string `json:"value"`
}

func (p Post) Validate(errors *binding.Errors, req *http.Request) {
    if len(p.Key) < 1 {
        errors.Add([]string{}, "PostError", "Too short; minimum 1 characters")
    } else if 120 < len(p.Key) {
        errors.Add([]string{}, "PostError", "Too long; maximum 120 characters")
    }
}

func main() {
    m := martini.Classic()
    m.Use(render.Renderer())

    m.Post("/api", binding.Json(Post{}), binding.ErrorHandler, func(post Post, r render.Render) {
        r.JSON(200, map[string]interface{}{"hello": "world"})
    })

    m.Run()
}
$ go run post_server.go
[martini] listening on :3000 (development)

別の端末から下記を実行。

$ curl -d '{"key":"1","value":""}' http://localhost:3000/api

content は下記が返却されます。

{"hello":"world"}

色々、拙い実装だとは思いますが、私が良く分から無い所が多い Golang 何で、兎に角、世(blog)に出します。