/
server.go
84 lines (72 loc) · 1.78 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
// Package burrow is a small framework for building web apps that accept HTTP, JSON-RPC and WebSocket requests and use
// the same business logic.
package burrow
import (
"net/http"
"github.com/gorilla/mux"
)
type App struct {
Prefix string
Name string
Methods []Method
Debug bool
Port string
Router *mux.Router
TLSCertificate *string
TLSPrivateKey *string
}
func (app *App) Run() error {
r := mux.NewRouter()
r.StrictSlash(true)
routes := &RouteHandler{Prefix: app.Prefix}
routes.MountRoutes(app.Methods)
routes.Subrouter(r)
app.Router = r
return app.start()
}
func (app *App) RunTLS(cert, key *string) error {
app.TLSCertificate = cert
app.TLSPrivateKey = key
return app.Run()
}
func NewApp(name string) *App {
return &App{
Name: name,
Prefix: "/",
Debug: false,
Port: "8080",
}
}
func (app *App) start() (err error) {
info("%s used Burrow!", app.Name)
app.mountStatic()
http.Handle("/", app.Router)
if app.hasCerts() {
err = app.serveTLS()
} else {
err = app.serve()
}
check(err)
return
}
func (app *App) serve() (err error) {
info("Now serving unencrypted HTTP traffic on port :%s", app.Port)
return http.ListenAndServe(app.GetPort(), nil)
}
func (app *App) serveTLS() (err error) {
port := app.GetPort()
cert := *app.TLSCertificate
key := *app.TLSPrivateKey
info("Now serving encrypted TLS traffic on port :%s", app.Port)
return http.ListenAndServeTLS(port, cert, key, nil)
}
func (app *App) mountStatic() {
static := http.StripPrefix("/static/", http.FileServer(http.Dir("./static/")))
app.Router.PathPrefix("/static/").Handler(static)
}
func (app *App) hasCerts() bool {
return (app.TLSCertificate != nil) && (app.TLSPrivateKey != nil)
}
func (app *App) GetPort() string {
return ":" + app.Port
}