LoginSignup
0
0

【Go言語】echoでパスのグループ化をする

Posted at

echoについて

echoはLabStack LLCという企業が開発を行っているマイクロフレームワークです。
Goのマイクロフレームワークといえばechoginのどちらかという感じが個人的にあります。

グルーピングについて

echoでAPIを開発しているとき、以下のように同じようなパスが複数できることがあります。特にAPIであれば/api/v1などを先頭に付けたりすることになるでしょうから、この手間を省きたいですよね。

func main() {
    e := echo.New()
    e.GET("/api/v1/xxx", func(c echo.Context) error {
        return c.String(http.StatusOK, "xxx")
    })
    e.GET("/api/v1/yyy", func(c echo.Context) error {
        return c.String(http.StatusOK, "yyy")
    })
    e.GET("/api/v1/zzz", func(c echo.Context) error {
        return c.String(http.StatusOK, "zzz")
    })
    
    e.Logger.Fatal(e.Start(":1323"))
}

グルーピングする

以下のようにechoにはGroupという機能があります。これを利用すること以下のように/api/v1のパスでまとめることができます。

func main() {
    e := echo.New()
    e.GET("/", func(c echo.Context) error {
        return c.String(http.StatusOK, "Hello World")
    })
    
    g := e.Group("/api/v1")
    g.GET("/api/v1/xxx", func(c echo.Context) error {
        return c.String(http.StatusOK, "xxx")
    })
    g.GET("/api/v1/yyy", func(c echo.Context) error {
        return c.String(http.StatusOK, "yyy")
    })
    g.GET("/api/v1/zzz", func(c echo.Context) error {
        return c.String(http.StatusOK, "zzz")
    })
    
    e.Logger.Fatal(e.Start(":1323"))
}
0
0
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
0
0