-
Notifications
You must be signed in to change notification settings - Fork 0
/
response.go
53 lines (40 loc) · 1.31 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
52
53
package alox
import (
"encoding/json"
"mime"
"net/http"
"path/filepath"
"strings"
"golang.org/x/net/html"
)
type ResponseMethods interface {
WriteJSON(responseWriter http.ResponseWriter, json []byte)
WriteHTML(responseWriter http.ResponseWriter, html []byte)
}
func WriteJSON(responseWriter http.ResponseWriter, json []byte) {
responseWriter.Header().Set("Content-Type", "application/json")
responseWriter.Write(json)
}
func WriteHTML(responseWriter http.ResponseWriter, html []byte) {
responseWriter.Header().Set("Content-Type", "text/html")
responseWriter.Write(html)
}
func WriteFile(responseWriter http.ResponseWriter, name string, data []byte) {
header := responseWriter.Header()
nameParts := strings.Split(name, ".")
header.Set("Content-Type", mime.TypeByExtension("."+nameParts[len(nameParts)-1]))
header.Set("Content-Type", mime.TypeByExtension(filepath.Ext(name)))
responseWriter.Write(data)
}
func MarshalAndWriteJSON(responseWriter http.ResponseWriter, value interface{}) (err error) {
var data []byte
if data, err = json.Marshal(value); err != nil {
return
}
WriteJSON(responseWriter, data)
return
}
func RenderAndWriteHTMLNode(responseWriter http.ResponseWriter, node *html.Node) (err error) {
responseWriter.Header().Set("Content-Type", "text/html")
return html.Render(responseWriter, node)
}