プログラミング逆引き辞典

~ 多言語対応のプログラミングレシピ ~

Go Ginフレームワーク使い方(超初級編)

■前提条件

Git Hubのアカウントが作成済みであること
 
 


■Gitのインストール

git for windowsの公式サイトからダウンロード
 

git for windows

 
 


■Ginのインストール

任意のフォルダを作成して、Git Bashを起動し、Ginフレームワークをクローンする
 

git clone https://github.com/gin-gonic/gin.git

 
 


■コントローラー作成

controllersフォルダを作成し、「controller.go」ファイルを作成する
 

package main

import (
    "net/http"

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

func main() {
    r := gin.Default()
    r.LoadHTMLGlob("../views/index.html")
    r.GET("/", func(ctx *gin.Context) {
        ctx.HTML(http.StatusOK, "index.html", gin.H{})
    })
    r.Run(":8080")
}

 
 


■表示画面作成

viewsフォルダを作成し、「index.html」ファイルを作成する
 

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>test index</title>
    </head>
    <body>
        <h1>Hello, World!</h1>
    </body>
</html>

 
 


■実行

「controller.go」ファイルを選択した状態で、「F5」を押下
 
ブラウザに「localhost:8080」と入力すると「Hello, World!」と表示される