-
Notifications
You must be signed in to change notification settings - Fork 0
/
goserve.go
128 lines (106 loc) · 2.86 KB
/
goserve.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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package main
import (
"flag"
"fmt"
"net/http"
"os"
"os/signal"
"strings"
"syscall"
)
// Parameters structure
type Parameters struct {
port string
route string
}
var (
port = flag.String("port", ":8000", "Defines the port to serve to.")
verbose = flag.Bool("verbose", false, "Turn on verbose logging")
versionFlag = flag.Bool("version", false, "Print version and exit")
cors string
version string
commit string
buildDate string
)
func init() {
flag.StringVar(&cors, "cors", "", "Set Access-Control-Allow-Origin Header, e.g. -cors '*'")
}
// osSignal captchers signals sent by the OS. This is used to close / exit the program
func osSignal(err chan<- error) {
osc := make(chan os.Signal)
signal.Notify(osc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
err <- fmt.Errorf("%s", <-osc)
}
// logRequest logs part of the HTTP Request to the
// command line
func logRequest(request *http.Request) {
if *verbose {
fmt.Printf("%s %s%s %s %s\n", request.Method, request.Host, request.RequestURI, request.Header["Referer"], request.Header["User-Agent"])
}
}
// handles serving of files through http
func handler(w http.ResponseWriter, r *http.Request) {
route := r.URL.Path[1:]
w.Header().Set("Access-Control-Allow-Origin", cors)
http.ServeFile(w, r, route)
logRequest(r)
}
// Normalize the port by adding a colon (:) in front of
// the port number so it can be used with http.ListenAndServe
func normalizePort(oldPort string) string {
// get the old port
newPort := oldPort
// Check if there is a colon (:) inside
index := strings.Index(newPort, ":")
// If not, prepend one
if index == -1 {
newPort = ":" + newPort
}
// return the normalized port
return newPort
}
// Generate the Parameters Object from flags
func generateParameterObject() *Parameters {
// Normalize the port.
port := normalizePort(*port)
// Create a new Parameters instance
params := new(Parameters)
// Assign port and entry point
params.port = port
// route is static for now.
params.route = "/"
// Return the Parameters instance
return params
}
func printVersion() {
if version == "" {
version = "dev"
}
fmt.Printf("Version: %s\n", version)
if buildDate != "" {
fmt.Printf("Build Date: %s\n", buildDate)
}
if commit != "" {
fmt.Printf("Commit %[1]s\nhttps://github.com/kevingimbel/goserve/tree/%[1]s", commit)
}
os.Exit(0)
}
// initialize the parameters and start the server.
func main() {
// Parse command line flags
flag.Parse()
// If -version is provided output version information
if *versionFlag {
printVersion()
}
params := generateParameterObject()
errch := make(chan error)
go osSignal(errch)
http.HandleFunc(params.route, handler)
go func() {
fmt.Println("Server is running on port", params.port)
errch <- http.ListenAndServe(params.port, nil)
}()
exit := <-errch
fmt.Println("Stopping Service. Reason:", exit)
}