Go で RESTful API

使ったフレームワーク

  • gorp
  • gin

whitech0c0late.hatenablog.com

RESTful API

理想のサンプルがあったので、これ動かしてみる

gist.github.com

  • Struct とマッピングして、JSON 返したりしてる
  • 生クエリ書いててわかりやすい
  • Struct にハマらない値返したいときは、どうする?

User の Struct 使わないで、そのまま key, value 書いて返すとかすればいいのかな

-     content := &User{
-          Id:        user_id,
-          Firstname: user.Firstname,
-          Lastname:  user.Lastname,
+       content := gin.H{
+           "Id":        user_id,
+           "Firstname": user.Firstname,
+           "Lastname":  user.Lastname,
+           "Fullname":  user.Firstname + " " + user.Lastname,
        }
        c.JSON(200, content)

ひとまず起動

  • routing 一覧とかでる
  • 本番では、env, mode セットするのかな
$ go run main.go
[GIN-debug] [WARNING] Now Gin requires Go 1.6 or later and Go 1.7 will be required soon.

[GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached.

[GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production.
 - using env:   export GIN_MODE=release
 - using code:  gin.SetMode(gin.ReleaseMode)

[GIN-debug] GET    /api/v1/users             --> main.GetUsers (4 handlers)
[GIN-debug] GET    /api/v1/users/:id         --> main.GetUser (4 handlers)
[GIN-debug] POST   /api/v1/users             --> main.PostUser (4 handlers)
[GIN-debug] PUT    /api/v1/users/:id         --> main.UpdateUser (4 handlers)
[GIN-debug] DELETE /api/v1/users/:id         --> main.DeleteUser (4 handlers)
[GIN-debug] OPTIONS /api/v1/users             --> main.OptionsUser (4 handlers)
[GIN-debug] OPTIONS /api/v1/users/:id         --> main.OptionsUser (4 handlers)
[GIN-debug] Listening and serving HTTP on :8080

リクエスト送ってみる

$ curl -i -X POST -H "Content-Type: application/json" -d "{ \"firstname\": \"Thea\", \"lastname\": \"Queen\" }" http://localhost:8080/api/v1/users
HTTP/1.1 201 Created
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Date: Mon, 13 Aug 2018 14:45:18 GMT
Content-Length: 46

{"id":1,"firstname":"Thea","lastname":"Queen"}

$ curl -s -XGET -H "Content-Type: application/json" localhost:8080/api/v1/users |jq .
[
  {
    "id": 1,
    "firstname": "Thea",
    "lastname": "Queen"
  }
]

$ curl -s -XGET -H "Content-Type: application/json" localhost:8080/api/v1/users/1 |jq .
{
  "Firstname": "Thea",
  "Fullname": "Thea Queen",
  "Id": 1,
  "Lastname": "Queen"
}

ログもわかりやすい

[GIN] 2018/08/13 - 23:45:18 | 201 |   63.406338ms |             ::1 | POST     /api/v1/users
[GIN] 2018/08/13 - 23:46:24 | 200 |     995.147µs |             ::1 | GET      /api/v1/users
[GIN] 2018/08/13 - 23:46:30 | 200 |    2.123372ms |             ::1 | GET      /api/v1/users/1

TODO

追記

medium.com

元記事と、gorm を使った例はここにある
複雑な構成じゃないときは、gorp でやったほうがわかりやすいかも