-
Notifications
You must be signed in to change notification settings - Fork 7.3k
/
response_transfer.go
70 lines (57 loc) · 1.27 KB
/
response_transfer.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
package app
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
)
type PluginResponseWriter struct {
bytes.Buffer
headers http.Header
statusCode int
}
func (rt *PluginResponseWriter) Header() http.Header {
if rt.headers == nil {
rt.headers = make(http.Header)
}
return rt.headers
}
func (rt *PluginResponseWriter) WriteHeader(statusCode int) {
rt.statusCode = statusCode
}
// From net/http/httptest/recorder.go
func parseContentLength(cl string) int64 {
cl = strings.TrimSpace(cl)
if cl == "" {
return -1
}
n, err := strconv.ParseInt(cl, 10, 64)
if err != nil {
return -1
}
return n
}
func (rt *PluginResponseWriter) GenerateResponse() *http.Response {
res := &http.Response{
Proto: "HTTP/1.1",
ProtoMajor: 1,
ProtoMinor: 1,
StatusCode: rt.statusCode,
Header: rt.headers.Clone(),
}
if res.StatusCode == 0 {
res.StatusCode = http.StatusOK
}
res.Status = fmt.Sprintf("%03d %s", res.StatusCode, http.StatusText(res.StatusCode))
if rt.Len() > 0 {
res.Body = ioutil.NopCloser(rt)
} else {
res.Body = http.NoBody
}
res.ContentLength = parseContentLength(rt.headers.Get("Content-Length"))
return res
}