フレームワーク「GIN」を使ってみた(スタイルシートやテンプレートの呼び出し方)


GETやスタイルシート、テンプレートの呼び出し方の備忘録

フォルダ構成

.
├── 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)

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

    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) {
    c.HTML(http.StatusOK, "layout.html", gin.H{
        "name": "Taro",
    })
}

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) {
    c.JSON(200, gin.H{
        "name": "taro",
    })
}

テンプレートファイル

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;
}

実行結果