Repository navigation
Expand file tree
/
Copy pathapp.go
More file actions
59 lines (51 loc) · 1.66 KB
/
Copy pathapp.go
File metadata and controls
59 lines (51 loc) · 1.66 KB
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
package main
import (
"log"
"net/http"
"os"
)
func main() {
logger := log.New(os.Stdout, "http: ", log.LstdFlags)
logger.Println("Server is starting on http://localhost:8000/...")
handleSameSiteCookies := func(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// Don't allow caching
w.Header().Add("Cache-Control", "no-cache")
if r.URL.Path == "/" {
// Set the header directly as go 1.10 doesn't support SameSite
// Set two cookies, one without SameSite and one with
w.Header().Add("Set-Cookie", "Auth1=auth1; SameSite=Lax")
w.Header().Add("Set-Cookie", "Auth2=auth2")
} else {
// Read the two cookies. If we're missing either, serve a 404
auth2, err2 := r.Cookie("Auth2")
if err2 != nil || auth2.Value != "auth2" {
w.Header().Add("Location", "/login")
w.WriteHeader(http.StatusSeeOther)
w.Write([]byte("303 - Missing auth2 cookie"))
return
}
auth1, err1 := r.Cookie("Auth1")
if err1 != nil || auth1.Value != "auth1" {
w.Header().Add("Location", "/login")
w.WriteHeader(http.StatusSeeOther)
w.Write([]byte("303 - Missing auth1 cookie"))
return
}
}
h.ServeHTTP(w, r)
}
}
http.Handle("/", logging(logger)(handleSameSiteCookies(http.FileServer(http.Dir("static")))))
http.ListenAndServe(":8000", nil)
}
func logging(logger *log.Logger) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
logger.Println(r.Method, r.URL.Path, r.Header.Get("Range"), r.Header.Get("Cookie"))
}()
next.ServeHTTP(w, r)
})
}
}