- 追加された行はこの色です。
- 削除された行はこの色です。
#author("2020-07-12T11:01:11+00:00","","")
#mynavi(Go言語)
#setlinebreak(on);
* 概要 [#j4dc7b3b]
#html(<div class="pl10">)
Go で簡単なWebAPIサーバを書いてみる。
尚、ここではWebフレームワークとして Gin を使用する。
#html(</div>)
* 目次 [#a93371f0]
#contsnts
#contents
- 参考
-- https://github.com/gin-gonic/gin
* 概要 [#j4dc7b3b]
#html(<div>)
#TODO
* インストール [#dac044ed]
#html(<div class="pl10">)
ginのインストール
#myterm2(){{
go get -u github.com/gin-gonic/gin
}}
#html(</div>)
* ファイル構成 [#x7179478]
#html(<div>)
#TODO
* サンプル作成 [#bb6d273c]
#html(<div class="pl10">)
まずは gin の Quick start の通りに書いてみる。
※ https://github.com/gin-gonic/gin#installation
main.go
#mycode2(){{
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong!",
})
})
r.Run()
}
}}
実行
#myterm2(){{
go run main.go
[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)
}}
動作確認
#myterm2(){{
curl -v http://localhost:8080/ping
* About to connect() to localhost port 8080 (#0)
* Trying 127.0.0.1... connected
* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET /ping HTTP/1.1
> User-Agent: curl/7.21.4 (x86_64-apple-darwin12.2.0) libcurl/7.21.4 OpenSSL/0.9.8} zlib/1.2.11 libidn/1.20
> Host: localhost:8080
> Accept: */*
>
< HTTP/1.1 200 OK
< Content-Type: application/json; charset=utf-8
< Date: Sun, 12 Jul 2020 11:19:18 GMT
< Content-Length: 19
<
* Connection #0 to host localhost left intact
* Closing connection #0
{"message":"pong!"}
}}
問題なさそう。
c.JSON でレスポンスを返却しているからか、Content-Type もちゃんと application/json になっている点は楽で良い。
#html(</div>)
* 入力値の受け取り [#c8e3d948]
#html(<div class="pl10">)
ここからは gin での作法になるが、リクエストデータから入力値を受け取って、編集したメッセージを返却するサンプルを作成する。
main.go
#mycode2(){{
package main
import (
"github.com/gin-gonic/gin"
"net/http"
"fmt"
)
// リクエストデータの定義
type JsonRequest struct {
Name string `json:"name"`
Age int `json:"age"`
Sex string `json:"sex"`
}
func main() {
r := gin.Default()
r.GET("/emp/:id", func(c *gin.Context) {
id := c.Param("id") // パスパラメータの受け取り
param1 := c.Query("param1") // クエリ文字列の受け取り
message := fmt.Sprintf("id: %s, param1: %s", id, param1)
c.JSON(http.StatusOK, gin.H{
"message": message,
})
})
r.POST("/emp", func(c *gin.Context) {
// JSONデータの受け取りは構造体を使用する
var json JsonRequest
if err := c.ShouldBindJSON(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// フォームデータはPostFormで受け取る
//name := c.PostForm("name")
//age := c.PostForm("age")
//sex := c.PostForm("sex")
message := fmt.Sprintf("name: %s, age: %d, sex: %s", json.Name, json.Age, json.Sex)
c.JSON(http.StatusOK, gin.H{
"message": message,
})
})
r.Run()
}
}}
動作確認
#myterm2(){{
curl -XPOST --data '{"name": "Taro", "age": 20, "sex": "man"}' -H "Content-Type: app;ication/json" http://localhost:8080/emp
{"message":"name: Taro, age: 20, sex: man"}
}}
#html(</div>)
* HTTPヘッダの追加/変更 [#g001dd66]
#html(<div class="pl10">)
gin.Context.Header で設定する事ができる。
例)
#mycode2(){{
func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
c.Header("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
}}
#html(</div>)