-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhelpers.go
87 lines (68 loc) · 1.91 KB
/
helpers.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
87
package helpers
import (
"encoding/json"
"net/http"
"github.com/gitkoDev/pokemon-api/models"
log "github.com/sirupsen/logrus"
)
type ErrResponseJSON struct {
ErrMsg string `json:"error"`
}
type MsgResponseJSON struct {
Msg string `json:"message"`
}
func RespondWithMessage(w http.ResponseWriter, receivedMsg string, status int) {
w.Header().Set("Content-type", "application/json")
w.WriteHeader(status)
// Init new msg struct
msg := MsgResponseJSON{Msg: receivedMsg}
err := json.NewEncoder(w).Encode(msg)
if err != nil {
log.Println("error encoding json:", err)
}
}
func RespondWithError(w http.ResponseWriter, receivedError error, status int) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
// Init new error struct
errMsg := ErrResponseJSON{ErrMsg: receivedError.Error()}
err := json.NewEncoder(w).Encode(errMsg)
if err != nil {
log.Println("error encoding json:", err)
}
}
func DecodeAuthJSON(httpReq *http.Request) (models.SingInInput, error) {
var input models.SingInInput
decoder := json.NewDecoder(httpReq.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&input); err != nil {
return input, err
}
return input, nil
}
func DecodeTrainerJSON(httpReq *http.Request) (models.Trainer, error) {
trainer := models.Trainer{}
decoder := json.NewDecoder(httpReq.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&trainer); err != nil {
return trainer, err
}
return trainer, nil
}
func DecodePokemonJSON(httpReq *http.Request) (models.Pokemon, error) {
pokemon := models.Pokemon{}
err := json.NewDecoder(httpReq.Body).Decode(&pokemon)
if err != nil {
return models.Pokemon{}, err
}
return pokemon, nil
}
func WriteJSON(w http.ResponseWriter, data any, statusCode int) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
err := json.NewEncoder(w).Encode(data)
if err != nil {
return err
}
return nil
}