Skip to content

Commit

Permalink
Adding Content-Length if not present.
Browse files Browse the repository at this point in the history
If serving a file and the Content-Length is not set in respose
it will now be set to the size of the file served.
  • Loading branch information
thorsager committed Apr 28, 2024
1 parent 58425bc commit adaa68b
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,22 +109,42 @@ func main() {
w.Header().Add("Server", description)
}

w.WriteHeader(int(statusCodeFlag))
if responseBodyFlag != "" && strings.HasPrefix(responseBodyFlag, "@") {
filename := trimFirst(responseBodyFlag)
s, err := os.Stat(filename)
if err != nil {
log.Printf("error: unable to stat file: '%s'", filename)
return
}
if w.Header().Get("Content-Length") == "" {
w.Header().Add("Content-Length", strconv.Itoa(int(s.Size())))
}
}

if responseBodyFlag != "" {
if strings.HasPrefix(responseBodyFlag, "@") {
// response is filename
filename := trimFirst(responseBodyFlag)
s, err := os.Stat(filename)
if err != nil {
log.Printf("error: unable to stat file: '%s'", filename)
return
}
file, err := os.Open(filename)
if err != nil {
log.Printf("error: unable to open file: '%s'", filename)
return
}
defer quietClose(file)
if w.Header().Get("Content-Length") == "" {
w.Header().Add("Content-Length", strconv.Itoa(int(s.Size())))
}
w.WriteHeader(int(statusCodeFlag)) // start sending body
if _, err = io.Copy(w, file); err != nil {
log.Printf("error: unable to write response body: %s", err)
}
} else {
w.WriteHeader(int(statusCodeFlag)) // start sending body
if _, err := w.Write([]byte(responseBodyFlag)); err != nil {
log.Printf("error: unable to write response body: %s", err)
}
Expand Down

0 comments on commit adaa68b

Please sign in to comment.