Deploying a net/http Go App
net/http is the standard HTTP server and client package in Go’s standard library, providing robust tools for building web servers and RESTful APIs. It’s widely used for its simplicity, performance, and deep integration with the Go ecosystem.
This guide explains how to deploy a Go application using the net/http package to Klutch.sh, both with and without a Dockerfile. It also covers installation and provides sample code to get started.
Prerequisites
- Go 1.20+
- Git and GitHub account
- Klutch.sh account
Getting Started: Install Go & Create App
- Create a new directory for your app and initialize a Go module:
Terminal window mkdir my-go-http-appcd my-go-http-appgo mod init my-go-http-app - Create a basic net/http app (
main.go
):package mainimport ("fmt""net/http""os")func handler(w http.ResponseWriter, r *http.Request) {fmt.Fprintln(w, "Hello from net/http on Klutch.sh!")}func main() {http.HandleFunc("/", handler)port := os.Getenv("PORT")if port == "" {port = "8080"}fmt.Printf("Server running on port %s\n", port)http.ListenAndServe(":"+port, nil)} - Test locally:
Visit http://localhost:8080 to see your app running.
Terminal window go run main.go
Deploying Without a Dockerfile
- Push your Go app to a GitHub repository.
- Log in to Klutch.sh.
- Create a new project and give it a name.
- Create a new app:
- Select your Go GitHub repository and branch
- Set the port to route traffic (usually 8080 for Go)
- Choose region, compute, number of instances, and add any environment variables
- Add a start command in your app settings:
Terminal window go run main.go - Click “Create” to deploy. Klutch.sh will build and deploy your app automatically.
Deploying With a Dockerfile
- Add a
Dockerfile
to your project root. Example:# Use official Golang image for buildFROM golang:1.20-alpine AS builderWORKDIR /appCOPY . .RUN go build -o go-http-app main.go# Use minimal image for runningFROM alpine:latestWORKDIR /appCOPY --from=builder /app/go-http-app .# Expose port (match your Go app)EXPOSE 8080# Start the appCMD ["./go-http-app"] - Push your code (with Dockerfile) to GitHub.
- In Klutch.sh, follow the same steps to create a project and app, but select the Dockerfile option when prompted.
- Set the service details and environment variables as needed.
- Click “Create” to deploy. Klutch.sh will build your Docker image and deploy your app.
Note: Your Go app should always listen on the PORT
environment variable as shown above.
Resources
Deploying to Klutch.sh is simple and flexible. Choose the method that best fits your workflow and project requirements.