-
Notifications
You must be signed in to change notification settings - Fork 0
/
header-echo.go
47 lines (40 loc) · 1.02 KB
/
header-echo.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
package main
import (
"encoding/json"
"flag"
"fmt"
"net/http"
"regexp"
)
var matcher regexp.Regexp
func respond(w http.ResponseWriter, r *http.Request) {
respondable := make(map[string]string)
for key, v := range r.Header {
if matcher.MatchString(key) {
respondable[key] = v[0]
}
}
var jsonResponse, err = json.MarshalIndent(respondable, "", " ")
if err != nil {
fmt.Fprint(w, err.Error())
} else {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-store")
w.Write(jsonResponse)
}
}
func handleRequests(port int, pattern string) {
matcherPtr := regexp.MustCompile(pattern)
matcher = *matcherPtr
http.HandleFunc("/echo", respond)
http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
}
func main() {
portPtr := flag.Int("port", 10001, "Port on which to listen")
patternPtr := flag.String("pattern", "^.*$", "Regex pattern to filter headers")
flag.Parse()
port := *portPtr
pattern := *patternPtr
fmt.Println("Listening on port:", port)
handleRequests(port, pattern)
}