diff options
author | Thomas Voss <mail@thomasvoss.com> | 2023-05-24 01:16:29 +0200 |
---|---|---|
committer | Thomas Voss <mail@thomasvoss.com> | 2023-05-24 01:16:29 +0200 |
commit | 4e7535fd73d232a51629fc33f65a61754a155b22 (patch) | |
tree | acce114d59f1679d8f08a4c96ed180b8027c632a /server.go |
Genesis commit
Diffstat (limited to 'server.go')
-rw-r--r-- | server.go | 98 |
1 files changed, 98 insertions, 0 deletions
diff --git a/server.go b/server.go new file mode 100644 index 0000000..502a038 --- /dev/null +++ b/server.go @@ -0,0 +1,98 @@ +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, lang, http.StatusMovedPermanently) + return + } + + path := r.URL.Path[1:] + parts := strings.Split(path, "/") + + _, err = r.Cookie("redirect") + if isSupportedLanguage(parts[0]) { + 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.StatusMovedPermanently) + 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:8000/" + } + + if err := os.Chdir("out"); err != nil { + panic(err) + } + http.HandleFunc("/", router) + log.Fatal(http.ListenAndServe(":8000", nil)) +} |