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.



Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay