-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
apikey.go
77 lines (64 loc) · 1.69 KB
/
apikey.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
package http
import (
"context"
"encoding/json"
"github.com/SyncYomi/SyncYomi/internal/domain"
"github.com/go-chi/chi/v5"
"github.com/go-chi/render"
"net/http"
)
type apikeyService interface {
Get(ctx context.Context, key string) (*domain.APIKey, error)
List(ctx context.Context) ([]domain.APIKey, error)
Store(ctx context.Context, key *domain.APIKey) error
Update(ctx context.Context, key *domain.APIKey) error
Delete(ctx context.Context, key string) error
ValidateAPIKey(ctx context.Context, token string) bool
}
type apikeyHandler struct {
encoder encoder
service apikeyService
}
func newAPIKeyHandler(encoder encoder, service apikeyService) *apikeyHandler {
return &apikeyHandler{
encoder: encoder,
service: service,
}
}
func (h apikeyHandler) Routes(r chi.Router) {
r.Get("/", h.list)
r.Post("/", h.store)
r.Delete("/{apikey}", h.delete)
}
func (h apikeyHandler) list(w http.ResponseWriter, r *http.Request) {
keys, err := h.service.List(r.Context())
if err != nil {
h.encoder.Error(w, err)
return
}
render.JSON(w, r, keys)
}
func (h apikeyHandler) store(w http.ResponseWriter, r *http.Request) {
var (
ctx = r.Context()
data domain.APIKey
)
if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
// encode error
h.encoder.StatusInternalError(w)
return
}
if err := h.service.Store(ctx, &data); err != nil {
// encode error
h.encoder.StatusInternalError(w)
return
}
h.encoder.StatusResponse(ctx, w, data, http.StatusCreated)
}
func (h apikeyHandler) delete(w http.ResponseWriter, r *http.Request) {
if err := h.service.Delete(r.Context(), chi.URLParam(r, "apikey")); err != nil {
h.encoder.StatusInternalError(w)
return
}
h.encoder.NoContent(w)
}