-
Notifications
You must be signed in to change notification settings - Fork 0
/
link.go
108 lines (88 loc) · 2.52 KB
/
link.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package link
import (
"encoding/json"
"net/http"
"strconv"
"time"
"github.com/gardod/shorty-api/internal/driver/http/response"
"github.com/gardod/shorty-api/internal/model"
"github.com/gardod/shorty-api/internal/service"
vld "github.com/go-ozzo/ozzo-validation/v4"
)
func list(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
q := r.URL.Query()
from := time.Now()
if param := q.Get("from"); param != "" {
var err error
from, err = time.Parse(time.RFC3339, param)
if err != nil {
response.JSON(w, vld.Errors{"from": err}, http.StatusBadRequest)
return
}
}
limit := 100
if param := q.Get("limit"); param != "" {
var err error
limit, err = strconv.Atoi(param)
if err != nil {
response.JSON(w, vld.Errors{"limit": err}, http.StatusBadRequest)
return
}
}
link, err := service.NewLink(ctx).Get(ctx, from, limit)
if err != nil {
response.JSON(w, response.ErrInternal, http.StatusInternalServerError)
return
}
response.JSON(w, link, http.StatusOK)
}
func insert(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
link := &model.Link{}
if err := json.NewDecoder(r.Body).Decode(&link.LinkRequest); err != nil {
response.JSON(w, response.ErrParse.Wrap(err), http.StatusBadRequest)
return
}
err := service.NewLink(ctx).Insert(ctx, link)
if err != nil {
if _, ok := err.(vld.Errors); ok {
response.JSON(w, response.ErrValidation.Wrap(err), http.StatusUnprocessableEntity)
return
}
response.JSON(w, response.ErrInternal, http.StatusInternalServerError)
return
}
response.JSON(w, link, http.StatusOK)
}
func get(w http.ResponseWriter, r *http.Request) {
response.JSON(w, GetLink(r.Context()), http.StatusOK)
}
func update(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
link := GetLink(ctx)
if err := json.NewDecoder(r.Body).Decode(&link.LinkRequest); err != nil {
response.JSON(w, response.ErrParse.Wrap(err), http.StatusBadRequest)
return
}
err := service.NewLink(ctx).Update(ctx, link)
if err != nil {
if _, ok := err.(vld.Errors); ok {
response.JSON(w, response.ErrValidation.Wrap(err), http.StatusUnprocessableEntity)
return
}
response.JSON(w, response.ErrInternal, http.StatusInternalServerError)
return
}
response.JSON(w, link, http.StatusOK)
}
func delete(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
link := GetLink(ctx)
err := service.NewLink(ctx).Delete(ctx, link)
if err != nil {
response.JSON(w, response.ErrInternal, http.StatusInternalServerError)
return
}
response.JSON(w, link, http.StatusOK)
}