DEV Community

kimihito
kimihito

Posted on • Originally published at kimihito.hatenablog.com on

1

EchoをVercel(Zeit now)のServerless Function上で動かす

TL;DR

// set api/index.go
package handler
import (
"net/http"
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
)
func hello(c echo.Context) error {
return c.String(http.StatusOK, "Hello World")
}
func hello2(c echo.Context) error {
return c.String(http.StatusOK, "Hello World2")
}
func Handler(w http.ResponseWriter, r *http.Request) {
e := echo.New()
e.Use(middleware.Logger())
e.Use(middleware.Recover())
e.GET("/api/", hello)
e.GET("/api/2", hello2)
e.ServeHTTP(w, r)
}
view raw index.go hosted with ❤ by GitHub
{
"name": "hoge",
"version": 2,
"routes": [
{ "src": "/api/.*", "dest": "api/index.go" }
]
}
view raw now.json hosted with ❤ by GitHub

Goやサーバレスアーキテクチャの初心者なので、もうちょっといいやり方ないかなーと持っています。

やりたいこと

Vercel(Zeit now)を使っていて、Serverless functionでGoが選択できたので利用してみたいと思ったので試してみた。

やったこと

ドキュメントにあるように プロジェクトルートに api ディレクトリを生成して date.go などつくる(このときhttp.HandleFuncのシグネチャである公開メソッドを用意すること)と /api/date というURLを提供できる( /api/ を指定したい場合は /api/index.go とする)。

が、今回はルーティングはEchoに任せたい(そもそもこれでいいのか?)と思ったので、 now.json の routes オプションを使い、 /api 配下に来たリクエストは /api/index.go で受け取って振り分けるようにした。

わかっていないこと

go.mod で module github.com/kimihito/hoge みたいな指定をすると、 now dev などで開発するとGitHubにアクセスしにいってしまう。 これがGo modのお作法なのか、 利用しているプラットフォームの動作なのかわかっていない(ょゎぃ)

参考にしたリンク

GitHub logo mini-eggs / go-now-example

Dev w/ Gin, deploy w/ Now.

Because this was slightly annoying to setup.

`$ ./scripts/dev.sh` to run locally.
`$ ./scripts/deploy.sh` to deploy.



DevCycle image

Fast, Flexible Releases with OpenFeature Built-in

Ship faster on the first feature management platform with OpenFeature built-in to all of our open source SDKs.

Start shipping

Top comments (0)

Feature flag article image

Create a feature flag in your IDE in 5 minutes with LaunchDarkly’s MCP server ⏰

How to create, evaluate, and modify flags from within your IDE or AI client using natural language with LaunchDarkly's new MCP server. Follow along with this tutorial for step by step instructions.

Read full post

👋 Kindness is contagious

Sign in to DEV to enjoy its full potential—unlock a customized interface with dark mode, personal reading preferences, and more.

Okay