Skip to content

Commit 9affafe

Browse files
authored
Merge pull request #98 from mutablelogic/v5
Added a function to write
2 parents 431c4d4 + 7e54449 commit 9affafe

File tree

1 file changed

+30
-3
lines changed

1 file changed

+30
-3
lines changed

pkg/httpresponse/write.go

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package httpresponse
22

33
import (
4+
"bytes"
5+
"fmt"
6+
"io"
47
"net/http"
58

69
// Packages
@@ -10,9 +13,10 @@ import (
1013
///////////////////////////////////////////////////////////////////////////////
1114
// PUBLIC METHODS
1215

13-
// Write a custom response to the writer with a HTTP status code,
14-
// leave the actual writing of the response to the caller
15-
func Write(w http.ResponseWriter, code int, contentType string) {
16+
// Write a custom response to the writer with a HTTP status code. If the custom
17+
// function is set and returns the number of bytes written (greater than zero), it will be used
18+
// to write the response body.
19+
func Write(w http.ResponseWriter, code int, contentType string, fn func(w io.Writer) (int, error)) error {
1620
if w.Header().Get(types.ContentTypeHeader) == "" {
1721
w.Header().Set(types.ContentTypeHeader, contentType)
1822
}
@@ -22,6 +26,29 @@ func Write(w http.ResponseWriter, code int, contentType string) {
2226
code = http.StatusOK
2327
}
2428

29+
// If fn is not nil, call it to write the response body
30+
var buf bytes.Buffer
31+
if fn != nil {
32+
n, err := fn(&buf)
33+
if err != nil {
34+
w.WriteHeader(http.StatusInternalServerError)
35+
return err
36+
}
37+
if n > 0 {
38+
w.Header().Set(types.ContentLengthHeader, fmt.Sprint(n))
39+
}
40+
}
41+
2542
// Write the status code
2643
w.WriteHeader(code)
44+
45+
// Write data
46+
if buf.Len() > 0 {
47+
if _, err := w.Write(buf.Bytes()); err != nil {
48+
return err
49+
}
50+
}
51+
52+
// Return success
53+
return nil
2754
}

0 commit comments

Comments
 (0)