Skip to content

Commit

Permalink
Content-Length on file serve (#3)
Browse files Browse the repository at this point in the history
* Adding Content-Length if not present.

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 authored Apr 28, 2024
1 parent 58425bc commit 465341a
Showing 1 changed file with 12 additions and 2 deletions.
14 changes: 12 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,26 +109,36 @@ func main() {
w.Header().Add("Server", description)
}

w.WriteHeader(int(statusCodeFlag))

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)
}
}
} else {
w.WriteHeader(int(statusCodeFlag))
}

if exitAfterFlag != 0 && exitAfterFlag == responseCount {
Expand Down

0 comments on commit 465341a

Please sign in to comment.