1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
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 {
if !errors.Is(err, http.ErrNoCookie) {
log.Println(err)
http.Error(w, "An error occured", http.StatusInternalServerError)
} else {
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],
Expires: time.Now().AddDate(100, 0, 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))
}
|