8000 Add header array parameter support by nicosommi · Pull Request #1 · inkel/lruc · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ Usage of lruc:
HTTP response code (default 200)
-content-type string
Content-Type (default "text/plain")
-header
HTTP response headers. Zero, one or more are accepted. Eg `-header "Access-Control-Allow-Origin: *" -header "Access-Control-Allow-Methods: POST, GET, OPTIONS"`
```

## License
Expand Down
24 changes: 23 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,32 @@ import (
"fmt"
"io"
"net/http"
"net/textproto"
"os"
"strings"
)

type headersMap textproto.MIMEHeader

func (i *headersMap) String() string {
return ""
}

func (i *headersMap) Set(value string) error {
v := strings.SplitN(value, ": ", 2)
(*i)[v[0]] = append((*i)[v[0]], v[1])
return nil
}

func main() {
var headers headersMap = make(map[string][]string)
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")
)
flag.Var(&headers, "header", "HTTP response headers. Zero, one or more are accepted")
flag.Parse()

bodyBytes := []byte(*body)
Expand All @@ -30,8 +46,14 @@ func main() {
}

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(*code)

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)
})

Expand Down
0