Skip to content

Instantly share code, notes, and snippets.

@andig
Last active July 18, 2024 20:40
Show Gist options
  • Save andig/8a0a3e1142e98eae8e456b8c03f96d1c to your computer and use it in GitHub Desktop.
Save andig/8a0a3e1142e98eae8e456b8c03f96d1c to your computer and use it in GitHub Desktop.
Go fly.io sticky session handler
package fly
import (
"net/http"
"os"
"time"
)
const (
flyMachineId = "fly-machine-id"
flyReplay = "Fly-Replay"
)
func Sticky(next http.HandlerFunc) http.HandlerFunc {
mid := os.Getenv("FLY_MACHINE_ID")
return func(w http.ResponseWriter, r *http.Request) {
if mid != "" {
cookie, err := r.Cookie(flyMachineId)
if err == nil && cookie.Value != mid {
w.Header().Set(flyReplay, mid)
w.WriteHeader(http.StatusTemporaryRedirect)
return
}
http.SetCookie(w, &http.Cookie{
Name: flyMachineId,
Value: mid,
Path: "/",
Expires: time.Now().Add(24 * time.Hour),
})
}
next(w, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment