forked from kennygrant/gohackernews
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.go
84 lines (66 loc) · 1.88 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 main
import (
"fmt"
"os"
"github.com/fragmenta/server"
"github.com/fragmenta/server/config"
"github.com/gnoirzox/gohackernews/src/app"
)
// Main entrypoint for the server which performs bootstrap, setup
// then runs the server. Most setup is delegated to the src/app pkg.
func main() {
// Bootstrap if required (no config file found).
if app.RequiresBootStrap() {
err := app.Bootstrap()
if err != nil {
fmt.Printf("Error bootstrapping server %s\n", err)
return
}
}
// Setup our server
server, err := SetupServer()
if err != nil {
fmt.Printf("server: error setting up %s\n", err)
return
}
// Inform user of server setup
server.Logf("#info Starting server in %s mode on port %d", server.Mode(), server.Port())
// In production, server
if server.Production() {
// Redirect all :80 traffic to our canonical url on :443
server.StartRedirectAll(80, server.Config("root_url"))
// If in production, serve over tls with autocerts from let's encrypt
err = server.StartTLSAutocert(server.Config("autocert_email"), server.Config("autocert_domains"))
if err != nil {
server.Fatalf("Error starting server %s", err)
}
} else {
// In development just serve with http on local port
err = server.Start()
if err != nil {
server.Fatalf("Error starting server %s", err)
}
}
}
// SetupServer creates a new server, and delegates setup to the app pkg.
func SetupServer() (*server.Server, error) {
// Setup server
s, err := server.New()
if err != nil {
return nil, err
}
// Load the appropriate config
c := config.New()
err = c.Load("secrets/fragmenta.json")
if err != nil {
return nil, err
}
config.Current = c
// Check environment variable to see if we are in production mode
if os.Getenv("FRAG_ENV") == "production" {
config.Current.Mode = config.ModeProduction
}
// Call the app to perform additional setup
app.Setup()
return s, nil
}