-
Notifications
You must be signed in to change notification settings - Fork 666
/
transport.go
72 lines (61 loc) · 1.71 KB
/
transport.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
// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0
package keys
import (
"context"
"encoding/json"
"log/slog"
"net/http"
"strings"
"github.com/absmach/magistrala/auth"
"github.com/absmach/magistrala/internal/api"
"github.com/absmach/magistrala/internal/apiutil"
"github.com/absmach/magistrala/pkg/errors"
"github.com/go-chi/chi/v5"
kithttp "github.com/go-kit/kit/transport/http"
)
const contentType = "application/json"
// MakeHandler returns a HTTP handler for API endpoints.
func MakeHandler(svc auth.Service, mux *chi.Mux, logger *slog.Logger) *chi.Mux {
opts := []kithttp.ServerOption{
kithttp.ServerErrorEncoder(apiutil.LoggingErrorEncoder(logger, api.EncodeError)),
}
mux.Route("/keys", func(r chi.Router) {
r.Post("/", kithttp.NewServer(
issueEndpoint(svc),
decodeIssue,
api.EncodeResponse,
opts...,
).ServeHTTP)
r.Get("/{id}", kithttp.NewServer(
(retrieveEndpoint(svc)),
decodeKeyReq,
api.EncodeResponse,
opts...,
).ServeHTTP)
r.Delete("/{id}", kithttp.NewServer(
(revokeEndpoint(svc)),
decodeKeyReq,
api.EncodeResponse,
opts...,
).ServeHTTP)
})
return mux
}
func decodeIssue(_ context.Context, r *http.Request) (interface{}, error) {
if !strings.Contains(r.Header.Get("Content-Type"), contentType) {
return nil, apiutil.ErrUnsupportedContentType
}
req := issueKeyReq{token: apiutil.ExtractBearerToken(r)}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, errors.Wrap(errors.ErrMalformedEntity, err)
}
return req, nil
}
func decodeKeyReq(_ context.Context, r *http.Request) (interface{}, error) {
req := keyReq{
token: apiutil.ExtractBearerToken(r),
id: chi.URLParam(r, "id"),
}
return req, nil
}