-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathresponse.go
More file actions
49 lines (41 loc) · 1.25 KB
/
response.go
File metadata and controls
49 lines (41 loc) · 1.25 KB
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
package fireball
import (
"log"
"net/http"
)
// Response is an object that writes to an http.ResponseWriter
// A Response object implements the http.Handler interface
type Response interface {
Write(http.ResponseWriter, *http.Request)
}
// ResponseFunc is a function which implements the Response interface
type ResponseFunc func(http.ResponseWriter, *http.Request)
func (rf ResponseFunc) Write(w http.ResponseWriter, r *http.Request) {
rf(w, r)
}
// HTTPResponse objects write the specified status, headers, and body to
// a http.ResponseWriter
type HTTPResponse struct {
Status int
Body []byte
Headers map[string]string
}
// NewResponse returns a new HTTPResponse with the specified status, body, and headers
func NewResponse(status int, body []byte, headers map[string]string) *HTTPResponse {
return &HTTPResponse{
Status: status,
Body: body,
Headers: headers,
}
}
// Write will write the specified status, headers, and body to the http.ResponseWriter
func (h *HTTPResponse) Write(w http.ResponseWriter, r *http.Request) {
for key, val := range h.Headers {
w.Header().Set(key, val)
}
w.WriteHeader(h.Status)
if _, err := w.Write(h.Body); err != nil {
log.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}