/
join.go
65 lines (58 loc) · 1.63 KB
/
join.go
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
package main
import (
"crypto/md5"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/a-know/yukizuri/trace"
"github.com/stretchr/objx"
)
type joinHandlerStruct struct {
next http.Handler
}
func (h *joinHandlerStruct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if cookie, err := r.Cookie("yukizuri"); err == http.ErrNoCookie || cookie.Value == "" {
// not joined yet
w.Header().Set("Location", "/join")
w.WriteHeader(http.StatusTemporaryRedirect)
} else if err != nil {
// something wrong
panic(err.Error())
} else {
// successful, call next wrapped handler
h.next.ServeHTTP(w, r)
}
}
func MustJoin(handler http.Handler) http.Handler {
return &joinHandlerStruct{next: handler}
}
// Path style : /join/{nickname}
func joinHandler(w http.ResponseWriter, r *http.Request) {
segs := strings.Split(r.URL.Path, "/")
if len(segs) == 3 {
nickname := segs[2]
m := md5.New()
io.WriteString(m, strings.ToLower(time.Now().String()))
uniqueID := fmt.Sprintf("%x", m.Sum(nil))
cookieValue := objx.New(map[string]interface{}{
"userid": uniqueID,
"name": nickname,
"avatar_url": "",
"email": "",
"remote_addr": r.Header.Get("X-Forwarded-For"),
}).MustBase64()
http.SetCookie(w, &http.Cookie{
Name: "yukizuri",
Value: cookieValue,
Path: "/"})
w.Header()["Location"] = []string{"/chat"}
w.WriteHeader(http.StatusTemporaryRedirect)
} else {
w.WriteHeader(http.StatusNotFound)
tracer := trace.New()
logContent := tracer.LogContent("system", "-", r.Header.Get("X-Forwarded-For"), "-")
tracer.TraceError(logContent, fmt.Errorf("Not supported request: %s", r.URL.Path))
}
}