Why Go for APIs?
Go compiles to a single binary with no runtime dependencies, handles concurrency natively with goroutines, and provides excellent performance. It's ideal for building fast, reliable API services.
Project Setup
mkdir myapi && cd myapi
go mod init myapiBasic HTTP Server
package main
import (
"encoding/json"
"log"
"net/http"
)
type Response struct {
Message string `json:"message"`
Status int `json:"status"`
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(Response{
Message: "OK",
Status: 200,
})
}
func main() {
http.HandleFunc("/health", healthHandler)
log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}Build and Deploy
# Build for Linux
GOOS=linux GOARCH=amd64 go build -o myapi
# Run on server
./myapiSystemd Service
[Unit]
Description=My Go API
After=network.target
[Service]
Type=simple
User=www-data
ExecStart=/opt/myapi/myapi
Restart=always
RestartSec=5
Environment="PORT=8080"
[Install]
WantedBy=multi-user.targetPerformance Tips
- Go's
net/httphandles thousands of concurrent connections out of the box - Use connection pooling for database access (
sql.DBdoes this automatically) - Profile with
go tool pprofto find bottlenecks - Use
sync.Poolfor frequently allocated objects