-
Notifications
You must be signed in to change notification settings - Fork 1
/
simple-webserver.go
74 lines (63 loc) · 1.43 KB
/
simple-webserver.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
package main
import (
"bytes"
"flag"
"fmt"
"log"
"net/http"
"os"
"strings"
"text/template"
"time"
"net/http/httputil"
)
var port string
var tmpl string
var responseTmpl *template.Template
const DEFAULT_TEMPLATE = `{
"name": "simple-webserver",
"date": "{{.Date}}",
"response": "OK"
}`
func main() {
flag.StringVar(&port, "port", "9090", "The port to serve on")
flag.StringVar(&tmpl, "template", "", "The response template")
flag.Parse()
if tmpl == "" {
tmpl = os.Getenv("TEMPLATE")
if tmpl == "" {
tmpl = DEFAULT_TEMPLATE
}
}
t, err := template.New("response-template").Parse(tmpl)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to parse template:\n %s", err)
os.Exit(1)
}
responseTmpl = t
bindPort := fmt.Sprintf(":%s", port)
log.Printf("Started simple web server on %s.", bindPort)
http.HandleFunc("/", handler)
http.ListenAndServe(bindPort, nil)
}
func handler(w http.ResponseWriter, r *http.Request) {
log.Println("Request:")
dump, err := httputil.DumpRequest(r, true)
if err == nil {
log.Println(string(dump))
}
data := make(map[string]string)
data["Date"] = time.Now().Format(time.RFC822)
for _, env := range os.Environ() {
splits := strings.Split(env, "=")
if len(splits[0]) > 0 {
data[splits[0]] = splits[1]
}
}
var response bytes.Buffer
responseTmpl.Execute(&response, data)
resp := response.String()
log.Println("Response:")
log.Printf("%s", resp)
fmt.Fprint(w, resp)
}