Add a flag to append a fixed HTTP header to all responses.

This commit is contained in:
Aparajit Raghavan 2017-05-30 05:01:51 +00:00
parent f643438420
commit c24df1f71d
2 changed files with 33 additions and 5 deletions

BIN
goStatic

Binary file not shown.

38
main.go
View file

@ -8,23 +8,51 @@ import (
"log" "log"
"net/http" "net/http"
"strconv" "strconv"
"strings"
) )
var ( var (
// Def of flags // Def of flags
portPtr = flag.Int("p", 8043, "The listening port") portPtr = flag.Int("p", 8043, "The listening port")
path = flag.String("static", "/srv/http", "The path for the static files") path = flag.String("static", "/srv/http", "The path for the static files")
headerFlag = flag.String("appendHeader", "", "HTTP response header, specified as `HeaderName:Value` that should be added to all responses.")
) )
func parseHeaderFlag(headerFlag string) (string, string) {
if len(headerFlag) == 0 {
return "", ""
}
pieces := strings.SplitN(headerFlag, ":", 2)
if len(pieces) == 1 {
return pieces[0], ""
}
return pieces[0], pieces[1]
}
func main() { func main() {
flag.Parse() flag.Parse()
port := ":" + strconv.FormatInt(int64(*portPtr), 10) port := ":" + strconv.FormatInt(int64(*portPtr), 10)
fs := http.FileServer(http.Dir(*path)) handler := http.FileServer(http.Dir(*path))
http.Handle("/", fs)
log.Println("Listening...") // Extra headers.
if len(*headerFlag) > 0 {
header, headerValue := parseHeaderFlag(*headerFlag)
if len(header) > 0 && len(headerValue) > 0 {
fileServer := handler
handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set(header, headerValue)
fileServer.ServeHTTP(w, r)
})
} else {
log.Println("appendHeader misconfigured; ignoring.")
}
}
http.Handle("/", handler)
log.Printf("Listening at 0.0.0.0%v...", port)
log.Fatalln(http.ListenAndServe(port, nil)) log.Fatalln(http.ListenAndServe(port, nil))
} }