-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
60 lines (52 loc) · 1.47 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
package main
import (
"bytes"
"flag"
"fmt"
"log"
"net/http"
"net/textproto"
"os"
"strings"
)
func main() {
var (
code = flag.Int("code", http.StatusOK, "HTTP response code")
ct = flag.String("content-type", "text/plain", "Content-Type")
body = flag.String("body", "Hello, World!", "Response body. Use `-` to read from stdin")
addr = flag.String("addr", ":8080", "Address to listen for requests")
)
headers := textproto.MIMEHeader{}
flag.Func("header", "HTTP response headers. Zero, one or more are accepted", func(value string) error {
v := strings.SplitN(value, ":", 2)
if len(v) != 2 {
return fmt.Errorf("header format must be key:value, got %s", value)
}
headers.Add(v[0], v[1])
return nil
})
flag.Parse()
var buf bytes.Buffer
if *body == "-" {
if _, err := buf.ReadFrom(os.Stdin); err != nil {
fmt.Fprintln(os.Stderr, "Cannot read from stdin:", err)
os.Exit(1)
}
} else {
buf.WriteString(*body)
}
bodyBytes := buf.Bytes()
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
log.Printf("method=%s uri=%q remote-addr=%v", r.Method, r.RequestURI, r.RemoteAddr)
for key, values := range headers {
for _, value := range values {
w.Header().Add(key, value)
}
}
w.Header().Set("Content-Type", *ct)
w.WriteHeader(*code)
w.Write(bodyBytes)
})
log.Printf(`msg="Starting lruc" addr=%v code=%d content-type=%q body-bytes=%d`, *addr, *code, *ct, len(bodyBytes))
fmt.Println(http.ListenAndServe(*addr, nil))
}