LoginSignup
2
2

More than 1 year has passed since last update.

【Go/Gin】手早くサイトを作るチートシート

Last updated at Posted at 2022-08-22

はじめに

とりあえず手早くサイトを作りたい、話はそれからだ、という人向けにGo, Ginを用いて手早くサイトを作るチートシートをここに残します。

まずはGinのインストール

コマンドプロントで下記を入力。

go get github.com/gin-gonic/gin

mainテンプレート

まずは基本骨格です。これをベースに味付けしていきます。

main.go
package main

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

func main() {
	router := gin.Default()
	router.LoadHTMLGlob("templates/*.html")

	//トップページ
	router.GET("/", func(ctx *gin.Context) {
		ctx.HTML(200, "top.html", gin.H{
		})
	})

	router.Run()
}

main.goと同じ階層にtemplatesディレクトリを作成し、その中に"top.html"を入れてください。
66.png
すると"top.html"の内容がまず最初に表示されます。

GoからHTMLに数値を渡す

Page1を作成します
このページはGoから数値を受け取ります。

次のスクリプトを、

main.go
//トップページ
router.GET("/", func(ctx *gin.Context) {
	ctx.HTML(200, "top.html", gin.H{
	})
})

の下(上でもいいですけど)に追加してください。

main.go
router.GET("/page1", func(ctx *gin.Context) {
	ctx.HTML(200, "page1.html", gin.H{
        "v1":"a",
        "v2":"b",
	})
})

下記page1.htmlもtop.htmlと同じくtemplatesディレクトリに入れてください。

page1.html
<!DOCTYPE html>
<html lang="jp">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {{.v1}}
    {{.v2}}
</body>
</html>

(サイトのURL)/page1にアクセスすると、page1.htmlが表示されますが、{{}}で囲まれた部分がGoで書いた数値に置き換わります。詳しくは「Go テンプレート」で検索!

URLを分解する

同じようなサイトを、IDによって分けたいとき、ありますよね。
次のように再現できます。

main.go
router.GET("/page2/:id", func(ctx *gin.Context) {
    n := ctx.Param("id")
	ctx.HTML(200, "page2.html", gin.H{
	})
})

上記のnに:idの値が代入されます。
例えば
(サイト名)/page2/5
にアクセスすると、nに5が代入されます。

HTMLのフォームの内容を受け取る

下記のようなサイトを考えます。

page3
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form method="post" action="/page3/submit">
        <p>Value 1
            <input type="text" name="value" size="30">
        </p>

        <p><input type="submit" value="Send"></p>
    </form>
</body>
</html>

こんなページです。
67.png
Sendボタンを押すと
(サイト名)/page3/submit
にリダイレクトします。

その処理はこちら。

main.go
//page3を映す分
router.GET("/page3", func(ctx *gin.Context) {
	ctx.HTML(200, "page3.html", gin.H{
	})
})

//page3の内容を受け取る
router.POST("/page3/submit", func(ctx *gin.Context) {
	value := ctx.PostForm("value")

    //page3にリダイレクト(これがないと真っ白のページで止まる)
	ctx.Redirect(302, "/page3")
})

このようにすると、フォームの内容を受け取れます。
上記の例だと、inputのnameがvalueなので、ctx.PostForm("value")にそれが格納されます。

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2