-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpHelpers.go
86 lines (73 loc) · 2.37 KB
/
httpHelpers.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
77
78
79
80
81
82
83
84
85
86
package methods
import (
"encoding/json"
"math"
"net/http"
"strconv"
"strings"
)
// ReturnObject - Model for ReturnObject
type ReturnObject struct {
Records any
Count Count
Links Links
}
// Count - Model for Count
type Count struct {
Total int `json:"total"`
Page int `json:"page"`
Limit int `json:"limit"`
SelfPagingToken string `json:"selfpagingtoken"`
PrevPagingToken string `json:"prevpagingtoken"`
NextPagingToken string `json:"nextpagingtoken"`
}
// Links - Model for Links
type Links struct {
Self string `json:"self"`
First string `json:"first"`
Prev string `json:"prev"`
Next string `json:"next"`
Last string `json:"last"`
}
/*
func (app *application) clientError(w http.ResponseWriter, status int) {
http.Error(w, http.StatusText(status), status)
}
*/
// RespondWithError - creating JSON response with error
func RespondWithError(w http.ResponseWriter, code int, err error) {
//trace := fmt.Sprintf("%s\n%s", err.Error(), debug.Stack())
//app.errorLog.Output(2, trace)
RespondWithJSON(w, code, map[string]string{"error": err.Error()})
}
// RespondWithJSON - creating JSON response
func RespondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, _ := json.MarshalIndent(payload, "", " ")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
// CreateLinks - Creating links for return object
func CreateLinks(r *http.Request, count Count) Links {
out := Links{}
page := count.Page
limit := count.Limit
total := count.Total
min := 1
max := int(math.Ceil(float64(total) / float64(limit)))
//TODO: check that page= must be higher than 1
out.Self = r.URL.RequestURI()
out.First = strings.Replace(out.Self, "page="+strconv.Itoa(count.Page), "page="+strconv.Itoa(min), 1)
if page <= 1 {
out.Prev = strings.Replace(out.Self, "page="+strconv.Itoa(count.Page), "page="+strconv.Itoa(min), 1)
} else {
out.Prev = strings.Replace(out.Self, "page="+strconv.Itoa(count.Page), "page="+strconv.Itoa(page-1), 1)
}
if page >= max {
out.Next = strings.Replace(out.Self, "page="+strconv.Itoa(count.Page), "page="+strconv.Itoa(max), 1)
} else {
out.Next = strings.Replace(out.Self, "page="+strconv.Itoa(count.Page), "page="+strconv.Itoa(page+1), 1)
}
out.Last = strings.Replace(out.Self, "page="+strconv.Itoa(count.Page), "page="+strconv.Itoa(max), 1)
return out
}