forked from Iwark/donuts-tech-calendar
/
main.go
81 lines (70 loc) · 1.86 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
package main
import (
"encoding/base64"
"flag"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"sync"
"text/template"
"github.com/Iwark/trace"
"github.com/gorilla/pat"
"github.com/joho/godotenv"
"github.com/markbates/goth"
"github.com/markbates/goth/providers/github"
)
type templateHandler struct {
once sync.Once
filename string
tpl *template.Template
}
func (t *templateHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t.once.Do(func() {
t.tpl = template.Must(template.ParseFiles("templates/application.html", filepath.Join("templates", t.filename)))
})
data := map[string]interface{}{
"Host": r.Host,
}
if authCookie, err := r.Cookie("auth"); err == nil {
name, err := base64.StdEncoding.DecodeString(authCookie.Value)
if err != nil {
fmt.Println("error:", err)
return
}
data["Name"] = string(name)
}
if err := t.tpl.ExecuteTemplate(w, "application", data); err != nil {
log.Fatal("TemplateExecute:", err)
}
}
var (
env = flag.String("env", "development", "環境")
addr = flag.String("addr", ":8080", "アプリケーションのアドレス")
)
func main() {
flag.Parse()
err := godotenv.Load(fmt.Sprintf("config/%s.env", *env))
if err != nil {
log.Fatal(err)
return
}
goth.UseProviders(
github.New(os.Getenv("GITHUB_CLIENT_KEY"), os.Getenv("GITHUB_SECRET"), os.Getenv("GITHUB_CALLBACK")),
)
p := pat.New()
r := newRoom()
r.tracer = trace.New(os.Stdout)
p.Add("GET", "/chat", MustAuth(&templateHandler{filename: "chat.html"}))
p.Add("GET", "/login", &templateHandler{filename: "login.html"})
p.Get("/auth/{action}/{provider}", loginHandler)
p.Add("GET", "/room", r)
// チャットルームの開始
go r.run()
// Webサーバの起動
log.Println("Webサーバーを開始します。ポート: ", *addr)
if err := http.ListenAndServe(*addr, p); err != nil {
log.Fatal("ListenAndServe:", err)
}
}