Implement API versioning in Go by using URL path prefixes (e.g., /v1/) and conditional logic based on the GODEBUG environment variable or go.mod directives to control behavior. Use the //go:debug directive in your source files to toggle specific behaviors for different versions without changing the core logic.
//go:debug default=go1.21
//go:debug panicnil=1
package main
import (
"net/http"
"os"
)
func main() {
// Check GODEBUG for version-specific behavior
if os.Getenv("GODEBUG") != "" {
http.HandleFunc("/v1/", handleV1)
http.HandleFunc("/v2/", handleV2)
} else {
http.HandleFunc("/", handleDefault)
}
http.ListenAndServe(":8080", nil)
}
func handleV1(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("API v1"))
}
func handleV2(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("API v2"))
}
func handleDefault(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Default API"))
}