From aefef66d7896415ecefa4f2a9af40b690befe198 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sa=C3=BAl=20Ortega?= Date: Thu, 1 Mar 2018 14:46:10 -0500 Subject: [PATCH] Create response.go --- response.go | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 response.go diff --git a/response.go b/response.go new file mode 100644 index 0000000..7084665 --- /dev/null +++ b/response.go @@ -0,0 +1,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 +}