-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelpers.go
69 lines (61 loc) · 1.33 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
package handlers
import (
"encoding/json"
"log"
"net/http"
"strconv"
"time"
"github.com/ramajd/events-api/errors"
"github.com/ramajd/events-api/objects"
)
type Response interface {
Json() []byte
StatusCode() int
}
func WriteResponse(w http.ResponseWriter, res Response) {
w.WriteHeader(res.StatusCode())
_, _ = w.Write(res.Json())
}
func WriteError(w http.ResponseWriter, err error) {
res, ok := err.(*errors.Error)
if !ok {
log.Println(err)
res = errors.ErrInternal
}
WriteResponse(w, res)
}
func IntFromString(w http.ResponseWriter, v string) (int, error) {
if v == "" {
return 0, nil
}
res, err := strconv.Atoi(v)
if err != nil {
log.Println(err)
WriteError(w, errors.ErrInvalidLimit)
}
return res, err
}
func Unmarshal(w http.ResponseWriter, data []byte, v interface{}) error {
if d := string(data); d == "null" || d == "" {
WriteError(w, errors.ErrObjectIsRequired)
return errors.ErrObjectIsRequired
}
err := json.Unmarshal(data, v)
if err != nil {
log.Println(err)
WriteError(w, errors.ErrBadRequest)
}
return err
}
func CheckSlot(slot *objects.TimeSlot) error {
if slot == nil {
return errors.ErrEventTimingIsRequired
}
if !slot.StartTime.After(time.Time{}) {
return errors.ErrInvalidTimeFormat
}
if !slot.EndTime.After(time.Time{}) {
return errors.ErrInvalidTimeFormat
}
return nil
}