-
Notifications
You must be signed in to change notification settings - Fork 13
/
transport.go
134 lines (113 loc) · 3.99 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
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
// Copyright (c) Mainflux
// SPDX-License-Identifier: Apache-2.0
package http
import (
"context"
"encoding/json"
"net/http"
"strings"
"github.com/MainfluxLabs/mainflux"
"github.com/MainfluxLabs/mainflux/internal/apiutil"
log "github.com/MainfluxLabs/mainflux/logger"
"github.com/MainfluxLabs/mainflux/pkg/errors"
"github.com/MainfluxLabs/mainflux/readers"
"github.com/MainfluxLabs/mainflux/webhooks"
kitot "github.com/go-kit/kit/tracing/opentracing"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/go-zoo/bone"
"github.com/opentracing/opentracing-go"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
const (
contentType = "application/json"
)
// MakeHandler returns a HTTP handler for API endpoints.
func MakeHandler(tracer opentracing.Tracer, svc webhooks.Service, logger log.Logger) http.Handler {
opts := []kithttp.ServerOption{
kithttp.ServerErrorEncoder(apiutil.LoggingErrorEncoder(logger, encodeError)),
}
r := bone.New()
r.Post("/webhooks/:thingID", kithttp.NewServer(
kitot.TraceServer(tracer, "create_webhooks")(createWebhooksEndpoint(svc)),
decodeWebhooksCreation,
encodeResponse,
opts...,
))
r.Get("/webhooks/:thingID", kithttp.NewServer(
kitot.TraceServer(tracer, "list_webhooks")(listWebhooksByThing(svc)),
decodeList,
encodeResponse,
opts...,
))
r.Handle("/metrics", promhttp.Handler())
return r
}
func decodeWebhooksCreation(_ context.Context, r *http.Request) (interface{}, error) {
if !strings.Contains(r.Header.Get("Content-Type"), contentType) {
return nil, apiutil.ErrUnsupportedContentType
}
req := createWebhooksReq{Token: apiutil.ExtractBearerToken(r), ThingID: bone.GetValue(r, "thingID")}
if err := json.NewDecoder(r.Body).Decode(&req.Webhooks); err != nil {
return nil, errors.Wrap(apiutil.ErrMalformedEntity, err)
}
return req, nil
}
func decodeList(_ context.Context, r *http.Request) (interface{}, error) {
req := listWebhooksReq{Token: apiutil.ExtractBearerToken(r), ThingID: bone.GetValue(r, "thingID")}
return req, nil
}
func encodeResponse(_ context.Context, w http.ResponseWriter, response interface{}) error {
w.Header().Set("Content-Type", contentType)
if ar, ok := response.(mainflux.Response); ok {
for k, v := range ar.Headers() {
w.Header().Set(k, v)
}
w.WriteHeader(ar.Code())
if ar.Empty() {
return nil
}
}
return json.NewEncoder(w).Encode(response)
}
func encodeError(_ context.Context, err error, w http.ResponseWriter) {
switch {
case errors.Contains(err, errors.ErrNotFound):
w.WriteHeader(http.StatusNotFound)
case errors.Contains(err, errors.ErrAuthentication),
err == apiutil.ErrBearerToken,
err == apiutil.ErrBearerKey:
w.WriteHeader(http.StatusUnauthorized)
case errors.Contains(err, errors.ErrAuthorization):
w.WriteHeader(http.StatusForbidden)
case errors.Contains(err, apiutil.ErrUnsupportedContentType):
w.WriteHeader(http.StatusUnsupportedMediaType)
case errors.Contains(err, apiutil.ErrInvalidQueryParams),
errors.Contains(err, apiutil.ErrMalformedEntity),
err == apiutil.ErrLimitSize,
err == apiutil.ErrInvalidIDFormat,
err == apiutil.ErrNameSize,
err == apiutil.ErrEmptyList,
err == apiutil.ErrMissingID,
err == ErrInvalidFormat,
err == ErrInvalidUrl:
w.WriteHeader(http.StatusBadRequest)
case errors.Contains(err, errors.ErrConflict):
w.WriteHeader(http.StatusConflict)
case errors.Contains(err, errors.ErrScanMetadata):
w.WriteHeader(http.StatusUnprocessableEntity)
case errors.Contains(err, readers.ErrReadMessages),
errors.Contains(err, errors.ErrCreateEntity):
w.WriteHeader(http.StatusInternalServerError)
case errors.Contains(err, errors.ErrCreateEntity),
errors.Contains(err, errors.ErrRetrieveEntity):
w.WriteHeader(http.StatusInternalServerError)
default:
w.WriteHeader(http.StatusInternalServerError)
}
if errorVal, ok := err.(errors.Error); ok {
w.Header().Set("Content-Type", contentType)
if err := json.NewEncoder(w).Encode(apiutil.ErrorRes{Err: errorVal.Msg()}); err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
}
}