This repository has been archived by the owner on Sep 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
controller.go
204 lines (175 loc) · 5.49 KB
/
controller.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package controllers
import (
"context"
"fmt"
"net/http"
"net/url"
"strconv"
"time"
model "github.com/cyruzin/feelthemovies/internal/app/models"
"github.com/cyruzin/feelthemovies/internal/pkg/logger"
"github.com/go-redis/redis"
jsoniter "github.com/json-iterator/go"
"golang.org/x/crypto/bcrypt"
validator "gopkg.in/go-playground/validator.v9"
)
var json = jsoniter.ConfigFastest
// Redis expiration time.
const redisTimeout = time.Duration(5 * time.Minute)
// Error messages.
const (
errDecode = "Could not decode the body request"
errParseInt = "Could not parse to int"
errParseFloat = "Could not parse to float"
errParseDate = "Could not parse the date"
errMarshal = "Could not marshal the payload"
errUnmarshal = "Could not unmarshal the payload"
errFetch = "Could not fetch the item"
errFetchRows = "Could not fetch the item total rows"
errKeySet = "Could not set the key"
errKeyUnlink = "Could not unlink the key"
errCreate = "Could not create the item"
errAttach = "Could not attach the items"
errSync = "Could not sync the items"
errUpdate = "Could not update the item"
errDelete = "Could not delete the item"
errSearch = "Could not do the search"
errPassHash = "Could not hash the password"
errAuth = "Could not authenticate"
errUnauthorized = "Unauthorized"
errEmptyToken = "JWT Token not provided"
errInvalidJWTToken = "Invalid JWT Token"
errMalformedToken = "Malformed token"
errGeneratingToken = "Could not generate the Token"
errQueryField = "The query field is required"
errEmptyRec = "The recommendation is empty, add at least one item"
errInternal = "Internal server error"
)
// Setup for handlers package.
type Setup struct {
model *model.Conn
redis *redis.Client
validator *validator.Validate
logger *logger.Logger
}
// New initiates the setup.
func New(
model *model.Conn,
redis *redis.Client,
validator *validator.Validate,
logger *logger.Logger,
) *Setup {
return &Setup{model, redis, validator, logger}
}
// CheckCache checks if the given key exists in cache.
func (s *Setup) CheckCache(ctx context.Context, key string, dest interface{}) (bool, error) {
cacheValue, _ := s.redis.WithContext(ctx).Get(key).Result()
if cacheValue != "" {
if err := s.UnmarshalBinary([]byte(cacheValue), dest); err != nil {
return false, err
}
return true, nil
}
return false, nil
}
// SetCache sets the given key in cache.
func (s *Setup) SetCache(ctx context.Context, key string, dest interface{}) error {
cacheValue, err := s.MarshalBinary(dest)
if err != nil {
return err
}
if err := s.redis.WithContext(ctx).Set(key, cacheValue, redisTimeout).Err(); err != nil {
return err
}
return nil
}
// RemoveCache removes the given key from the cache.
func (s *Setup) RemoveCache(ctx context.Context, key string) error {
val, _ := s.redis.WithContext(ctx).Get(key).Result()
if val != "" {
_, err := s.redis.Unlink(key).Result()
if err != nil {
return err
}
return nil
}
return nil
}
// GenerateCacheKey generates a cache key base on
// the given key and returns a string.
func (s *Setup) GenerateCacheKey(params url.Values, key string) string {
var cacheKey string
if params["page"] != nil && params["query"] == nil { // Only page param.
cacheKey = fmt.Sprintf("%s?page=%s", key, params["page"][0])
} else if params["page"] == nil && params["query"] != nil { // Only query param.
cacheKey = fmt.Sprintf("%s?query=%s", key, params["query"][0])
} else if params["page"] != nil && params["query"] != nil { // Both.
cacheKey = fmt.Sprintf("?query=%s&page=%s", params["query"][0], params["page"][0])
} else {
cacheKey = key
}
return cacheKey
}
// IDParser converts the given ID to int64.
func (s *Setup) IDParser(sid string) (int64, error) {
id, err := strconv.Atoi(sid)
if err != nil {
return 0, err
}
return int64(id), nil
}
// PageParser checks if page string exists in the
// given URL params. If exists, it will be parsed to
// int and returned. If some error occurs, the default
// value will be returned.
//
// Default value: 1.
func (s *Setup) PageParser(params url.Values) (int, error) {
newPage := 1
if params["page"] != nil && params["page"][0] != "" {
newPage, err := strconv.Atoi(params["page"][0])
if err != nil {
return newPage, err
}
return newPage, nil
}
return newPage, nil
}
// ToJSON returns a JSON response.
func (s *Setup) ToJSON(
w http.ResponseWriter,
httpStatus int,
dest interface{},
) {
w.WriteHeader(httpStatus)
json.NewEncoder(w).Encode(dest)
}
// MarshalBinary is a implementation of BinaryMarshaler interface.
func (s *Setup) MarshalBinary(d interface{}) ([]byte, error) {
data, err := json.Marshal(d)
if err != nil {
return nil, err
}
return data, nil
}
// UnmarshalBinary is a implementation of BinaryUnmarshaler interface.
func (s *Setup) UnmarshalBinary(d []byte, v interface{}) error {
err := json.Unmarshal(d, &v)
if err != nil {
return err
}
return nil
}
// HashPassword encrypts a given password using bcrypt algorithm.
func (s *Setup) HashPassword(password string, cost int) (string, error) {
bytes, err := bcrypt.GenerateFromPassword([]byte(password), cost)
if err != nil {
return "", err
}
return string(bytes), nil
}
// CheckPasswordHash checks if the given passwords matches.
func (s *Setup) CheckPasswordHash(password, hash string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}