-
Notifications
You must be signed in to change notification settings - Fork 0
/
respuesta.go
42 lines (39 loc) · 856 Bytes
/
respuesta.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
package go_tools
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
//Responder escribe en el response la respuesta establecida
func Responder(w http.ResponseWriter, estado int, error interface{}, mensaje string, datos interface{}, esJSON bool, debug bool) {
resp := struct {
Estado int `json:"estado"`
Error interface{} `json:"error"`
Mensaje string `json:"mensaje"`
Datos interface{} `json:"datos"`
}{
estado,
error,
mensaje,
datos,
}
log.Println(fmt.Sprintf("%#v", resp))
if esJSON {
if !debug {
resp.Error = nil
}
js, err := json.Marshal(resp)
if err == nil {
CleanCache(w)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(estado)
w.Write(js)
} else {
log.Println("Error Marshal JSON: ", err)
}
} else {
w.WriteHeader(estado)
w.Write([]byte(mensaje))
}
}