コピペコードで快適生活

明日使えるソースを自分のために

GoModulesを使ってパッケージ管理する

QuickStartメモ

# プロジェクトディレクトリを掘る
mkdir -p github.com/kinosuke01/gin-tutorial
cd github.com/kinosuke01/gin-tutorial/

# 初期化する → go.modというパッケージリストを保持するファイルができる
go mod init github.com/kinosuke01/gin-tutorial/
go: creating new go.mod: module github.com/kinosuke01/gin-tutorial/

# main.go書いてみる
cat main.go
=====
package main

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

func main() {
    fmt.Println("hello!!!")

    r := gin.Default()
    r.GET("/ping", func(c *gin.Context) {
        c.JSON(200, gin.H{
            "message": "pong",
        })
    })
    r.Run() // listen and serve on 0.0.0.0:8080
}
=====

# ビルドする
# 必要なパッケージが ${GOPATH}/pkg/* 以下に自動でインストールされてbuildされる。
# パッケージリストが go.mod に追記される
go build main.go

# 実行ファイルを実行する
./main
hello!!!
[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)

[GIN-debug] GET    /ping                     --> main.main.func1 (3 handlers)
[GIN-debug] Environment variable PORT is undefined. Using port :8080 by default
[GIN-debug] Listening and serving HTTP on :8080

参考にさせていただきました。 https://qiita.com/propella/items/e49bccc88f3cc2407745