フレームワーク「GIN」を使ってみた(リクエストパラメータ)


パラメータの取得

以下の形式から、パラメータを取得する

http://localhost:8080/hello?name=Taro
http://localhost:8080/hello/Ziro
http://localhost:8080/api/hello?name=Saburo
http://localhost:8080/api/hello/Shiro

フォルダ構成

.
├── main.go
├── asset
│   └── css
│       └── style.css
├── templates
│   ├── hello.html
│   └── layout.html
└── routes
    ├── routes.go
    └── api.go

MAIN

main.go
package main

import (
    "routes"
    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()

    // 事前にテンプレートをロード 相対パス
    // router.LoadHTMLGlob("templates/*/**") などもいけるらしい
    router.LoadHTMLGlob("templates/*.html")

    // 静的ファイルのパスを指定
    router.Static("/assets", "./assets")

    // ハンドラの指定
    router.GET("/hello", routes.Hello)
    router.GET("/hello/:name", routes.HelloParam)

    // グルーピング
    user := router.Group("/api")
    {
        user.GET("/hello", routes.HelloJson)
        user.GET("/hello/:name", routes.HelloJsonPram)
    }

    router.NoRoute(routes.NoRoute) // どのルーティングにも当てはまらなかった場合に処理
    router.Run(":8080")
}

ハンドラー

routes/routes.go
package routes

import (
    "net/http"
    "github.com/gin-gonic/gin"
)

func Hello(c *gin.Context) {
    name := c.DefaultQuery("name", "HOGE") // HOGEはデフォルト値?
    //name := c.Query("lastname") // デフォルトがない場合
    c.HTML(http.StatusOK, "layout.html", gin.H{
        "name": name,
    })
}

func HelloParam(c *gin.Context) {
    name := c.Param("name")
    c.HTML(http.StatusOK, "layout.html", gin.H{
        "name": name,
    })
}

func NoRoute(c *gin.Context) {
    // helloに飛ばす
    c.Redirect(http.StatusMovedPermanently, "/hello")
}
routes/api.go
package routes

import (
    "github.com/gin-gonic/gin"
)

func HelloJson(c *gin.Context) {
    name := c.DefaultQuery("name", "HOGE") // HOGEはデフォルト値?
    //name := c.Query("lastname") // デフォルトがない場合
    c.JSON(200, gin.H{
        "name": name,
    })
}

func HelloJsonPram(c *gin.Context) {
    name := c.Param("name")
    c.JSON(200, gin.H{
        "name": name,
    })
}

テンプレートファイル

templates/layouts.html
<html>
  <head>
    <link rel="stylesheet" href="assets/css/style.css">
    <title>Sample</title>
  </head>
  <body>
    <!-- Render the current template here -->
    {{template "content" .}}
  </body>
</html>
templates/hello.html
{{define "content"}}
<h2>Hello {{.name}}!</h2>
{{end}}

スタイルシート

assets/css/style.css
h2 {
    color: red;
}

実行結果

http://localhost:8080/hello

デフォルトの「HOGE」が表示される

http://localhost:8080/hello?name=Taro

http://localhost:8080/hello/Ziro

なぜか、スタイルシートが適用されない。

http://localhost:8080/api/hello?name=Saburo

http://localhost:8080/api/hello/Shiro