LoginSignup
17
11

More than 3 years have passed since last update.

GoでVercel Serverless Functions

Last updated at Posted at 2020-09-07

githubリポジトリ

ホスティングサービスをNetlifyからVercelに乗り換えたついでにServerless Functionsが気になったので試してみました。

Vercel

Next.jsの運営元であるVercel(元Zeit)のWebアプリケーションホスティングサービスです。ちょうどNetlifyとかと同じポジションですね。

前準備

アカウント作成

Vercelのトップページの右上にあるSignUpボタンからGithub, GitLab, BitBucketのアカウントを使用してアカウント作成をします。
vercelsignup.PNG

Vercel CLI

npmパッケージとして提供されているVercel CLIをインストールします。
これは主にローカルからデプロイを行う際に使用します。

npm
npm i -g vercel
yarn
yarn global add vercel

インストール後

vercel login

を実行し、上で登録したemailアドレスの入力と確認を済ませます。

サーバーレス関数の作成

プロジェクトフォルダの直下にindex.goを作成します。
このindex.gohttp.ResponseWriter*http.Requestを引数として持つ関数が存在する必要があります。
まずはVercel Serverless Functions Go Exampleというテキストを返すだけの関数を実装します。

index.js
package main

import (
  "fmt"
  "net/http"
)

func Handler(w http.ResponseWriter, r *http.Request) {
  fmt.Fprintf(w, "Vercel Serverless Functions Go Example")
}

vercel.jsonの作成

vercel.json
{
  "version": 2,
  "name": "go",
  "builds": [
    { "src": "*.go", "use": "@vercel/go" }
  ]
}

ルーティング

日時を返すエンドポイントを作成していきます。
今回はわかりやすく下記のようにエンドポイントごとにフォルダを分けて作成します。

root
├ /date
│ └ index.go
└ index.go

型の作成

date/index.go
type ResDate struct {
    Date string `json:"date"`
}

リクエストハンドラの実装

w.Header().Set("Content-Type", "application/json")Content-Typeの指定を行います。

date/index.go
func Handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    d := ResDate{ time.Now().Format(time.RFC850) }
    bytes, _ := json.Marshal(d)
    fmt.Fprintf(w, string(bytes))
}

date/index.go

date/index.go
package date

import (
    "fmt"
    "net/http"
    "time"
    "encoding/json"
)

type ResDate struct {
    Date string `json:"date"`
}

func Handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    d := ResDate{ time.Now().Format(time.RFC850) }
    bytes, _ := json.Marshal(d)
    fmt.Fprintf(w, string(bytes))
}

vercel.jsonでルーティングの設定

ルーティングの設定を行うためにvercel.jsonroutesの要素を追加します。

routes
  "routes": [
    { "src": "/date", "dest": "/date" }
  ]

加えて、ビルド対象フォルダに先程作成したdateフォルダ内のgoファイルを追加します。

builds
  "builds": [
    { "src": "*.go", "use": "@vercel/go" },
    { "src": "/date/*.go", "use": "@vercel/go" }
  ]
vercel.json
{
  "version": 2,
  "name": "go-vercel-functions-demo",
  "builds": [
    { "src": "*.go", "use": "@vercel/go" },
    { "src": "/date/*.go", "use": "@vercel/go" }
  ],
  "routes": [
    { "src": "/date", "dest": "/date" }
  ]
}

デプロイ

vercel

これだけです。

本番デプロイをするのであれば--prodオプションをつけるだけです。

vercel --prod

2020/10/05 タイポがあったため修正しました。prob -> prod
@kimihito_ さん ご指摘ありがとうございます。

デプロイ後の以下のURLにアクセスすると
https://go-vercel-function-example.mugi111.vercel.app
一番最初に作成した関数通りVercel Serverless Functions Go Exampleと表示されているのが確認できました。
vercelroot.PNG

dateエンドポイントも正常に動作していることが確認できました。
https://go-vercel-function-example.mugi111.vercel.app/date
verceldate.PNG

17
11
1

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
17
11