forked from ngmoco/falcore
/
response.go
51 lines (46 loc) · 1.75 KB
/
response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package falcore
import (
"bytes"
"io"
"io/ioutil"
"net/http"
"strings"
)
// Generate an http.Response using the basic fields
// Use -1 for the contentLength if you don't know the content length in advance.
func SimpleResponse(req *http.Request, status int, headers http.Header, contentLength int64, body io.Reader) *http.Response {
res := new(http.Response)
res.StatusCode = status
res.ProtoMajor = 1
res.ProtoMinor = 1
res.ContentLength = contentLength
res.Request = req
res.Header = make(map[string][]string)
if body_rdr, ok := body.(io.ReadCloser); ok {
res.Body = body_rdr
} else if body != nil {
res.Body = ioutil.NopCloser(body)
}
if headers != nil {
res.Header = headers
}
return res
}
// Generate an http.Response using a []byte for the body.
func ByteResponse(req *http.Request, status int, headers http.Header, body []byte) *http.Response {
return SimpleResponse(req, status, headers, int64(len(body)), bytes.NewBuffer(body))
}
// Generate an http.Response using a string for the body.
func StringResponse(req *http.Request, status int, headers http.Header, body string) *http.Response {
return SimpleResponse(req, status, headers, int64(len(body)), strings.NewReader(body))
}
// Generate an http.Response using the read half of an io.Pipe as the Body.
// Returns the write half of an io.Pipe and the response.
//
// Use this to stream a generated body without buffering first. Don't forget to close the writer when finished.
// Writes are blocking until something Reads so you must use a separate goroutine for writing.
// Response will be Transfer-Encoding: chunked.
func PipeResponse(req *http.Request, status int, headers http.Header) (io.WriteCloser, *http.Response) {
pR, pW := io.Pipe()
return pW, SimpleResponse(req, status, headers, -1, pR)
}