-
Notifications
You must be signed in to change notification settings - Fork 249
/
Copy pathhttp_handler.go
55 lines (51 loc) · 1.23 KB
/
http_handler.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
package util
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
func Error(w http.ResponseWriter, r *http.Request, httpStatus int, obj string) (err error) {
return Json(w, r, httpStatus, map[string]string{
"error": obj,
})
}
func Json(w http.ResponseWriter, r *http.Request, httpStatus int, obj interface{}) (err error) {
var bytes []byte
if r.FormValue("pretty") != "" {
bytes, err = json.MarshalIndent(obj, "", " ")
} else {
bytes, err = json.Marshal(obj)
}
if err != nil {
log.Printf("Marshal Error %v : %v", err, obj)
return
}
callback := r.FormValue("callback")
if callback == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(httpStatus)
_, err = w.Write(bytes)
if err != nil {
log.Printf("Write Error %v : %v", err, string(bytes))
return
}
} else {
w.Header().Set("Content-Type", "application/javascript")
w.WriteHeader(httpStatus)
if _, err = w.Write([]uint8(callback)); err != nil {
log.Printf("Write1 Error %v", err)
return
}
if _, err = w.Write([]uint8("(")); err != nil {
log.Printf("Write2 Error %v", err)
return
}
fmt.Fprint(w, string(bytes))
if _, err = w.Write([]uint8(")")); err != nil {
log.Printf("Write3 Error %v", err)
return
}
}
return
}