-
Notifications
You must be signed in to change notification settings - Fork 1
/
response.go
59 lines (46 loc) · 1.2 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
54
55
56
57
58
59
// This package parse a http request from datatables (jQuery plugin) to a friendly structure
// More details in https://github.com/saulortega/datatables
// import "github.com/saulortega/datatables"
package datatables
import (
"encoding/json"
"errors"
"net/http"
)
type Response struct {
Draw int `json:"draw"`
RecordsTotal int `json:"recordsTotal"`
RecordsFiltered int `json:"recordsFiltered"`
Data interface{} `json:"data"`
Error error `json:"error,omitempty"`
}
func (r *Response) Check() error {
var err error
if r.Data == nil || r.RecordsFiltered == 0 {
r.Data = []string{} //Vacío, no nulo
}
if r.RecordsFiltered > r.RecordsTotal {
err = errors.New("wrong filtered or total records")
}
return err
}
func (r *Response) WriteResponseOnSuccess(w http.ResponseWriter) error {
err := r.Check()
if err != nil {
return err
}
RJSON, err := json.Marshal(r)
if err != nil {
return err
}
w.WriteHeader(http.StatusOK)
w.Write(RJSON)
return nil
}
func (r *Response) WriteResponse(w http.ResponseWriter) error {
err := r.WriteResponseOnSuccess(w)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
return err
}