Using the Go Runtime with Vercel Functions
Use the Go runtime to deploy a Go HTTP server on Vercel. The Go Framework
Preset works with standard net/http servers and frameworks such as chi or
gin.
The Go Framework Preset
detects a root go.mod file and one of these entrypoints: main.go,
cmd/api/main.go, or cmd/server/main.go. Your server must listen on the
PORT environment variable.
Running a Go server requires the
framework preset to be set to go.
package main
import (
"fmt"
"log"
"net/http"
"os"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello from Go on Vercel")
})
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
log.Fatal(http.ListenAndServe(":"+port, mux))
}A minimal Go server that Vercel can run from main.go.
To deploy a Go server alongside a frontend such as a Next.js app within the same project, use Services.
Vercel reads the Go version from go.mod.
go.mod must be at the project root.
If go.mod does not declare a version, Vercel uses the latest supported Go
version.
The first time Vercel uses a Go version, it downloads and caches that toolchain. Later deployments using the same version reuse the cached toolchain.
Define dependencies in go.mod, and commit go.sum when it exists.
You can provide custom build flags by using the GO_BUILD_FLAGS
Environment Variable.
{
"$schema": "https://openapi.vercel.sh/vercel.json",
"build": {
"env": {
"GO_BUILD_FLAGS": "-ldflags '-s -w'"
}
}
}An example -ldflags flag with -s -w. This will remove debug information
from the output file. This is the default value when no GO_BUILD_FLAGS are
provided.
You can also place .go files inside an /api directory. Each file that
exports an http.HandlerFunc becomes a separate Vercel Function. The Go runtime
will automatically detect the go.mod file at the root of your Project to
install dependencies.
package handler
import (
"fmt"
"net/http"
)
func Handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "<h1>Hello from Go!</h1>")
}The function name can be any exported Go identifier as long as it matches 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:token@github.com.
All major Git providers are supported, including GitHub, GitLab, Bitbucket, and self-hosted Git servers.
With GitHub, you need to create a personal token with permission to access your private repository.
Was this helpful?