Using the Go Runtime with Serverless Functions
Learn how to use the Go runtime to compile Go Serverless Functions on Vercel.The Go runtime is used by Vercel to compile Go Serverless Functions that expose a single HTTP handler, from a .go
file within an /api
directory at your project's root.
For example, define an index.go
file inside an /api
directory as follows:
package handler
import (
"fmt"
"net/http"
)
func Handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>Hello from Go!</h1>")
}
For advanced usage, such as using private packages with your Go projects, see the Advanced Go Usage section.
The exported function needs to include the
HandlerFunc
signature type, but can use any
valid Go exported function declaration as the function name.
The Go runtime will automatically detect the go.mod
file at the root of your Project to determine the version of Go to use.
If go.mod
is missing or the version is not defined, the default version 1.20 will be used.
The first time the Go version is detected, it will be automatically downloaded and cached. Subsequent deployments using the same Go version will use the cached Go version instead of downloading it again.
The Go runtime will automatically detect the go.mod
file at the root of your Project to install dependencies.
You can provide custom build flags by using the GO_BUILD_FLAGS
Environment Variable.
{
"build": {
"env": {
"GO_BUILD_FLAGS": "-ldflags '-s -w'"
}
}
}
In order to use this runtime, no configuration is needed. You only need to create a file inside the api
directory.
The entry point of this runtime is a global matching .go
files that export a function that implements the http.HandlerFunc
signature.
To install private packages with go get
, add an Environment Variable named GIT_CREDENTIALS
.
The value should be the URL to the Git repo including credentials, such as https://username:[email protected]
.
All major Git providers are supported including GitHub, GitLab, Bitbucket, as well as a self-hosted Git server.
With GitHub, you will need to create a personal token with permission to access your private repository.
Was this helpful?