package main import ( "errors" "log" "net/http" "os" "strings" "time" ) var url string const CookieName = "eurothomasvosscom_users-language" func isSupportedLanguage(lang string) bool { if len(lang) != 2 { return false } _, err := os.Stat(lang) return !os.IsNotExist(err) } func router(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "Method is not supported.", http.StatusMethodNotAllowed) return } var lang string cookie, err := r.Cookie(CookieName) if err != nil && !errors.Is(err, http.ErrNoCookie) { log.Println(err) http.Error(w, "An error occured", http.StatusInternalServerError) return } else if err != nil { lang = "en" } else { lang = cookie.Value } if r.URL.Path == "/" { http.SetCookie(w, &http.Cookie{ Name: "redirect", Path: "/", }) http.Redirect(w, r, url + lang + "/", http.StatusTemporaryRedirect) return } path := r.URL.Path[1:] parts := strings.Split(path, "/") _, err = r.Cookie("redirect") if isSupportedLanguage(parts[0]) && parts[0] != lang { if r.Header.Get("Referer") == "" && err != nil { parts[0] = lang path = strings.Join(parts, "/") http.SetCookie(w, &http.Cookie{ Name: "redirect", Path: "/", }) http.Redirect(w, r, url + path, http.StatusTemporaryRedirect) return } if r.Header.Get("Referer") != "" { http.SetCookie(w, &http.Cookie{ Name: CookieName, Value: parts[0], Path: "/", }) } } if err == nil { http.SetCookie(w, &http.Cookie{ Name: "redirect", Expires: time.Unix(0, 0), Path: "/", }) } http.ServeFile(w, r, path) } func main() { if len(os.Args) == 2 { url = os.Args[1] } else { url = "http://localhost:4729/" } if err := os.Chdir("done"); err != nil { panic(err) } http.HandleFunc("/", router) log.Fatal(http.ListenAndServe(":4729", nil)) }