LoginSignup
14
14

More than 5 years have passed since last update.

前回はgomを使ってパッケージ管理してみたのを、新たにGBというのがあると聞いて、そっちも試してみました。

GBの特徴はプロジェクトに必要なコードを全てvendoringする事。
いわゆるプロジェクトベースと呼ばれるツールな事。くわしくはここを見るといいかも?

さっそくGBをインストールしましょう。

$ go get github.com/constabulary/gb/...

GBはプロジェクトのディレクトリ構造が独特です。
ソースは必ずsrcディレクトリに、さらにsrc直下は実行できず、かならずパッケージディレクトリを作る必要があります。

~/code/demo-project $ tree -d .       
.                                                                   
├── src                               
│   └── hello

こんな感じでディレクトリを作ります。

次にginをインストールしましょう。
GBではgo getのかわりにgb vendor fetchを使います。

$ gb vendor fetch github.com/gin-gonic/gin

するとvendorというディレクトリができ、中にgin関連のsrcが配置されます。
このvendorはブランチを指定したり、updateするなど、様々な機能があります。
詳しくはここを見るといいです。

その際にvendorディレクトリにはmanifestファイルが生成されます。
json形式でbranchやrevisionが記述されているファイルで、他の人はこのファイルを元にgb vendor restoreを行うと同じ環境をつくれるという仕組みです。

では実際にmain.goを作ってhelloディレクトリに格納しましょう。

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

    // This handler will match /user/john but will not match neither /user/ or /user
    router.GET("/user/:name", func(c *gin.Context) {
        name := c.Param("name")
        c.String(http.StatusOK, "Hello %s", name)
    })

    // However, this one will match /user/john/ and also /user/john/send
    // If no other routers match /user/john, it will redirect to /user/join/
    router.GET("/user/:name/*action", func(c *gin.Context) {
        name := c.Param("name")
        action := c.Param("action")
        message := name + " is " + action
        c.String(http.StatusOK, message)
    })

    router.Run(":8080")
}

GBは単体の.goのファイルの実行やビルドはサポートしていません。
なので実行するには一度ビルドをする必要があります。

$ gb build
$ bin/hello
[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   /user/:name               --> main.main.func1 (3 handlers)
[GIN-debug] GET   /user/:name/*action       --> main.main.func2 (3 handlers)
[GIN-debug] Listening and serving HTTP on :8080

こんな感じで実行できます。
ブラウザから http://localhost:8080/user/oresama 等と打って動作確認してみましょう。

14
14
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
14
14