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.



AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay