This repository has been archived by the owner on Mar 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
utils.go
76 lines (64 loc) · 1.78 KB
/
utils.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
71
72
73
74
75
76
package photoshare
import (
"encoding/json"
"fmt"
"github.com/juju/errgo"
"net/http"
"strconv"
"strings"
)
func writeBody(w http.ResponseWriter, body []byte, status int, contentType string) error {
w.Header().Set("Content-Type", contentType+"; charset=UTF8")
w.Header().Set("Content-Length", strconv.Itoa(len(body)))
w.WriteHeader(status)
_, err := w.Write(body)
return errgo.Mask(err)
}
func renderJSON(w http.ResponseWriter, value interface{}, status int) error {
body, err := json.Marshal(value)
if err != nil {
return errgo.Mask(err)
}
return writeBody(w, body, status, "application/json")
}
func renderString(w http.ResponseWriter, status int, msg string) error {
return writeBody(w, []byte(msg), status, "text/plain")
}
func getScheme(r *http.Request) string {
if r.TLS == nil {
return "http"
}
return "https"
}
func getBaseURL(r *http.Request) string {
return fmt.Sprintf("%s://%s", getScheme(r), r.Host)
}
func decodeJSON(r *http.Request, value interface{}) error {
return errgo.Mask(json.NewDecoder(r.Body).Decode(value))
}
// Converts a Pg Array (returned as string) to an int slice
func pgArrToIntSlice(pgArr string) []int64 {
var items []int64
s := strings.TrimRight(strings.TrimLeft(pgArr, "{"), "}")
for _, value := range strings.Split(s, ",") {
if item, err := strconv.Atoi(strings.Trim(value, " ")); err == nil {
items = append(items, int64(item))
}
}
return items
}
// Converts an int slice to a Pg Array string
func intSliceToPgArr(items []int64) string {
var s []string
for _, value := range items {
s = append(s, strconv.FormatInt(value, 10))
}
return "{" + strings.Join(s, ",") + "}"
}
func getPage(r *http.Request) *page {
pageNum, err := strconv.ParseInt(r.FormValue("page"), 10, 64)
if err != nil {
pageNum = 1
}
return newPage(pageNum)
}