-
Notifications
You must be signed in to change notification settings - Fork 3
/
server.go
82 lines (66 loc) · 1.95 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
// Package server serves a web interface for interacting with dotfiles stored in a database.
package server
import (
"net/http"
"os"
"time"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/knoebber/dotfile/db"
"github.com/pkg/errors"
)
const timeout = 10 * time.Second
// Config configures the server.
type Config struct {
Addr string // Address to listen at.
DBPath string // The path to store the sqlite database file.
Secure bool // Tell the server code that the host is using https.
ProxyHeaders bool // Sets request IP from reverse proxy headers.
Host string // Overrides http.Request.Host when not empty.
SMTP *SMTPConfig // Sets up a SMTP Client
SMTPConfigPath string // Sets SMTP from this file's JSON when not empty.
}
// URL returns the configured url.
// If c.Host is not set it will use the requests host header.
func (c Config) URL(r *http.Request) string {
protocol := "http://"
if c.Secure {
protocol = "https://"
}
if c.Host == "" {
return protocol + r.Host
}
return protocol + c.Host
}
// New returns a dotfilehub web server.
// Expects an assets folder in the same directory from where the binary is ran.
func New(config Config) (*http.Server, error) {
var err error
if err = db.Start(config.DBPath); err != nil {
return nil, errors.Wrapf(err, "starting database")
}
if config.SMTPConfigPath != "" {
config.SMTP, err = smtpConfig(config.SMTPConfigPath)
if err != nil {
return nil, err
}
}
r := mux.NewRouter()
if err := setupRoutes(r, config); err != nil {
return nil, err
}
s := &http.Server{
Addr: config.Addr,
WriteTimeout: timeout,
ReadTimeout: timeout,
}
if config.ProxyHeaders {
s.Handler = handlers.LoggingHandler(os.Stdout, handlers.ProxyHeaders(r))
} else {
s.Handler = handlers.LoggingHandler(os.Stdout, r)
}
if err := loadTemplates(); err != nil {
return nil, err
}
return s, nil
}