/
server.go
91 lines (77 loc) · 2.4 KB
/
server.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
package main
import (
"fmt"
"github.com/ESCah/go-against-humanity/app/controllers"
"github.com/ESCah/go-against-humanity/app/game"
"github.com/ESCah/go-against-humanity/app/utils"
"github.com/gorilla/sessions"
"github.com/labstack/echo"
"github.com/labstack/echo-contrib/session"
"html/template"
"io"
"net/http"
"os"
)
type Template struct {
templates *template.Template
}
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
return t.templates.ExecuteTemplate(w, name, data)
}
func customHTTPErrorHandler(err error, c echo.Context) {
code := http.StatusInternalServerError
if he, ok := err.(*echo.HTTPError); ok {
code = he.Code
}
errorPage := fmt.Sprintf("%d.html", code)
if err := c.File(errorPage); err != nil {
c.Logger().Error(err)
}
fmt.Printf("At %s:\n\t", c.Path())
c.Logger().Error(err)
_ = c.String(http.StatusInternalServerError, err.Error())
}
func main() {
e := echo.New()
t := &Template{
templates: template.Must(template.New("").Funcs(utils.FuncMap).ParseGlob("app/views/**/*.html")),
}
cookieSecret, found := os.LookupEnv("COOKIE_SECRET")
if !found {
panic("Please set the environment variable COOKIE_SECRET to a random string.")
}
e.Use(session.Middleware(sessions.NewCookieStore([]byte(cookieSecret))))
e.Renderer = t
e.HTTPErrorHandler = customHTTPErrorHandler
var mm = new(game.MatchManager)
var ws = controllers.MakeSocketServer(e, mm)
w := controllers.WebApp{
MatchManager: mm,
Echo: e,
Db: utils.InitDB(),
Ws: ws,
}
e.Static("/public", "public")
e.File("/favicon.ico", "public/img/favicon.ico")
e.GET("/login", w.Login)
e.POST("/login", w.DoLogin)
e.GET("/signup", w.SignUp)
e.POST("/signup", w.DoSignUp)
e.GET("/logout", w.Logout)
e.GET("/admin", w.Admin)
e.GET("/admin/users", w.AdminUsers)
// Todo: make RESTful
e.GET("/admin/matches/new", w.AdminNewMatch)
e.PUT("/admin/matches/:id/new_black_card", w.NewBlackCard)
e.PUT("/admin/matches/:id/end_voting", w.EndVoting)
e.GET("/matches", w.Matches)
e.GET("/matches/join/:id", w.JoinMatch)
e.GET("/matches/join_latest", w.JoinLatestMatch)
e.GET("/mycards", w.MatchCards)
e.PUT("/matches/:match_id/pick_card/:card_id", w.PickCard)
e.PUT("/matches/:match_id/vote_card/:card_id", w.VoteCard)
e.GET("/", w.Index)
// The ws start is not blocking, but the echo start is, so ws goes first
ws.Start()
e.Logger.Debug(e.Start(":80"))
}