-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
100 lines (83 loc) · 2.33 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
// Copyright (C) 2018 - 2020 Sam Olds
package main
import (
"context"
"flag"
"log"
"net/http"
"os"
"strings"
"github.com/samolds/port/httplog"
"github.com/samolds/port/server"
)
// TODO: support a config file
var (
tcpPort = flag.String("port", "", "port to listen on")
staticDir = flag.String("static-dir", "",
"absolute path to directory with static assets")
gaeProjectID = flag.String("gae-project-id", "",
"the project id for this google app engine project")
gaeCredFile = flag.String("gae-cred-file", "",
"the path to the credential file for google app engine")
relHTMLTmplDir = flag.String("rel-html-tmpl-dir", "",
"the relative path to the directory with all of the html templates")
)
// GAE uses environment variables
const (
tcpPortEV = "PORT"
staticDirEV = "STATIC_DIR"
gaeProjectIDEV = "GAE_PROJECT_ID"
gaeCredFileEV = "GAE_CRED_FILE"
relHTMLTmplDirEV = "REL_HTML_TMPL_DIR"
)
// main you know what this is.
func main() {
flag.Parse()
envVarCheck()
err := runner()
if err != nil {
log.Fatalf("failed: %v", err)
}
}
// runner is the "real" main so that we can be idiomatic and just return errors
// everywhere, and main is just responsible for calling log.Fatalf on errors.
func runner() error {
opts := server.Options{
StaticDir: *staticDir,
GAEProjectID: *gaeProjectID,
GAECredFile: *gaeCredFile,
RelHTMLTmplDir: *relHTMLTmplDir,
}
ctx := context.Background()
server, err := server.New(ctx, opts)
if err != nil {
return err
}
return http.ListenAndServe(*tcpPort, httplog.LogResponses(server))
}
// envVarCheck is to be called after flag.Parse() to check to see if no flags
// were provided. if no flags were provided, it's probably because it's running
// on stupid GAE and is expecting environment variables instead. dumb
func envVarCheck() {
flags := *tcpPort != "" ||
*staticDir != "" ||
*gaeProjectID != "" ||
*gaeCredFile != "" ||
*relHTMLTmplDir != ""
if flags {
return
}
*tcpPort = os.Getenv(tcpPortEV)
*staticDir = os.Getenv(staticDirEV)
*gaeProjectID = os.Getenv(gaeProjectIDEV)
*gaeCredFile = os.Getenv(gaeCredFileEV)
*relHTMLTmplDir = os.Getenv(relHTMLTmplDirEV)
// prepend ":" to the port if it wasn't provided by dumb gae
p := *tcpPort
if len(p) == 0 {
panic("port is required")
}
if !strings.HasPrefix(p, ":") {
*tcpPort = ":" + p
}
}