/
main.go
93 lines (76 loc) · 2.22 KB
/
main.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
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
package main
import (
"blueprints/trace"
"flag"
"github.com/stretchr/signature"
"log"
"net/http"
"os"
"path/filepath"
"text/template"
"github.com/stretchr/gomniauth"
"github.com/stretchr/gomniauth/providers/google"
"github.com/stretchr/objx"
)
var avatars Avatar = TryAvatars{
UseFileSystemAvatar,
UseAuthAvatar,
UseGravatar}
// templ represents a single template
type templateHandler struct {
filename string
templ *template.Template
}
// ServeHTTP handles the HTTP request.
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if t.templ == nil {
t.templ = template.Must(template.ParseFiles(filepath.Join("templates", t.filename)))
}
data := map[string]interface{}{
"Host": r.Host,
}
log.Println("Host:", r.Host)
if authCookie, err := r.Cookie("auth"); err == nil {
data["UserData"] = objx.MustFromBase64(authCookie.Value)
log.Println("UserData:", data)
}
t.templ.Execute(w, data)
}
func main() {
var addr = flag.String("addr", ":8080", "The addr of the application")
flag.Parse() // parse the flag
gomniauth.SetSecurityKey(signature.RandomKey(64))
gomniauth.WithProviders(
google.New("605169096484-hvgf6b5u60cdv0krm7r106b1v4lsuvk9.apps.googleusercontent.com",
"0F1iTCjapfcoFUupsINMc-6X", "http://localhost:8080/auth/callback/google"),
)
r := newRoom()
r.tracer = trace.New(os.Stdout)
http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: "auth",
Value: "",
Path: "/",
MaxAge: -1,
})
w.Header()["Location"] = []string{"/chat"}
w.WriteHeader(http.StatusTemporaryRedirect)
})
http.Handle("/chat",
MustAuth(&templateHandler{filename: "chat.html"}))
http.Handle("/login",
&templateHandler{filename: "login.html"})
http.Handle("/upload", &templateHandler{filename: "upload.html"})
http.Handle("/avatars/",
http.StripPrefix("/avatars/", http.FileServer(http.Dir("./avatars"))))
http.HandleFunc("/uploader", uploaderHandler)
http.HandleFunc("/auth/", loginHandler)
http.Handle("/room", r)
// get the room going
go r.run()
// start the web server
log.Println("Starting web server on", *addr)
if err := http.ListenAndServe(*addr, nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}