/
main.go
94 lines (77 loc) · 2.56 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
94
package main
import (
"flag"
"log"
"net/http"
"os"
"path/filepath"
"text/template"
"github.com/matryer/goblueprints/chapter1/trace"
"github.com/stretchr/gomniauth"
"github.com/stretchr/gomniauth/providers/facebook"
"github.com/stretchr/gomniauth/providers/github"
"github.com/stretchr/gomniauth/providers/google"
"github.com/stretchr/objx"
)
// set the active Avatar implementation
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,
}
if authCookie, err := r.Cookie("auth"); err == nil {
data["UserData"] = objx.MustFromBase64(authCookie.Value)
}
t.templ.Execute(w, data)
}
var host = flag.String("host", ":8080", "The host of the application.")
func main() {
flag.Parse() // parse the flags
// setup gomniauth
gomniauth.SetSecurityKey("98dfbg7iu2nb4uywevihjw4tuiyub34noilk")
gomniauth.WithProviders(
github.New("3d1e6ba69036e0624b61", "7e8938928d802e7582908a5eadaaaf22d64babf1", "http://localhost:8080/auth/callback/github"),
google.New("44166123467-o6brs9o43tgaek9q12lef07bk48m3jmf.apps.googleusercontent.com", "rpXpakthfjPVoFGvcf9CVCu7", "http://localhost:8080/auth/callback/google"),
facebook.New("537611606322077", "f9f4d77b3d3f4f5775369f5c9f88f65e", "http://localhost:8080/auth/callback/facebook"),
)
r := newRoom()
r.tracer = trace.New(os.Stdout)
http.Handle("/chat", MustAuth(&templateHandler{filename: "chat.html"}))
http.Handle("/login", &templateHandler{filename: "login.html"})
http.HandleFunc("/auth/", loginHandler)
http.Handle("/room", r)
http.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
http.SetCookie(w, &http.Cookie{
Name: "auth",
Value: "",
Path: "/",
MaxAge: -1,
})
w.Header().Set("Location", "/chat")
w.WriteHeader(http.StatusTemporaryRedirect)
})
http.Handle("/upload", &templateHandler{filename: "upload.html"})
http.HandleFunc("/uploader", uploaderHandler)
http.Handle("/avatars/",
http.StripPrefix("/avatars/",
http.FileServer(http.Dir("./avatars"))))
// get the room going
go r.run()
// start the web server
log.Println("Starting web server on", *host)
if err := http.ListenAndServe(*host, nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}