Last active
July 18, 2024 20:40
-
-
Save andig/8a0a3e1142e98eae8e456b8c03f96d1c to your computer and use it in GitHub Desktop.
Go fly.io sticky session handler
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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