MG-30 - Auth: Migrate from bone to chi (#47)

* Migrate from bone to chi

Signed-off-by: felix.gateru <felix.gateru@gmail.com>

* Migrate from bone to chi

Signed-off-by: felix.gateru <felix.gateru@gmail.com>

* Add subroutes

Signed-off-by: felix.gateru <felix.gateru@gmail.com>

* Update auth service

Signed-off-by: felix.gateru <felix.gateru@gmail.com>

* update bootstrap

Signed-off-by: felix.gateru <felix.gateru@gmail.com>

* Update multiplexer

Signed-off-by: felix.gateru <felix.gateru@gmail.com>

* Refactor user and things handler

Signed-off-by: felix.gateru <felix.gateru@gmail.com>

* Refactor user and things handler

Signed-off-by: felix.gateru <felix.gateru@gmail.com>

---------

Signed-off-by: felix.gateru <felix.gateru@gmail.com>
This commit is contained in:
Felix Gateru
2023-11-27 20:57:44 +03:00
committed by GitHub
parent eb019eefed
commit 004782dd49
20 changed files with 302 additions and 295 deletions
+8 -8
View File
@@ -13,7 +13,7 @@ import (
"github.com/absmach/magistrala/internal/apiutil"
mfclients "github.com/absmach/magistrala/pkg/clients"
"github.com/absmach/magistrala/pkg/errors"
"github.com/go-zoo/bone"
"github.com/go-chi/chi/v5"
)
func decodeCreateDomainRequest(_ context.Context, r *http.Request) (interface{}, error) {
@@ -33,7 +33,7 @@ func decodeCreateDomainRequest(_ context.Context, r *http.Request) (interface{},
func decodeRetrieveDomainRequest(_ context.Context, r *http.Request) (interface{}, error) {
req := retrieveDomainRequest{
token: apiutil.ExtractBearerToken(r),
domainID: bone.GetValue(r, "domainID"),
domainID: chi.URLParam(r, "domainID"),
}
return req, nil
}
@@ -45,7 +45,7 @@ func decodeUpdateDomainRequest(_ context.Context, r *http.Request) (interface{},
req := updateDomainReq{
token: apiutil.ExtractBearerToken(r),
domainID: bone.GetValue(r, "domainID"),
domainID: chi.URLParam(r, "domainID"),
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -71,7 +71,7 @@ func decodeListDomainRequest(ctx context.Context, r *http.Request) (interface{},
func decodeEnableDomainRequest(_ context.Context, r *http.Request) (interface{}, error) {
req := enableDomainReq{
token: apiutil.ExtractBearerToken(r),
domainID: bone.GetValue(r, "domainID"),
domainID: chi.URLParam(r, "domainID"),
}
return req, nil
}
@@ -79,7 +79,7 @@ func decodeEnableDomainRequest(_ context.Context, r *http.Request) (interface{},
func decodeDisableDomainRequest(_ context.Context, r *http.Request) (interface{}, error) {
req := disableDomainReq{
token: apiutil.ExtractBearerToken(r),
domainID: bone.GetValue(r, "domainID"),
domainID: chi.URLParam(r, "domainID"),
}
return req, nil
}
@@ -91,7 +91,7 @@ func decodeAssignUsersRequest(_ context.Context, r *http.Request) (interface{},
req := assignUsersReq{
token: apiutil.ExtractBearerToken(r),
domainID: bone.GetValue(r, "domainID"),
domainID: chi.URLParam(r, "domainID"),
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, errors.Wrap(apiutil.ErrValidation, errors.Wrap(err, errors.ErrMalformedEntity))
@@ -107,7 +107,7 @@ func decodeUnassignUsersRequest(_ context.Context, r *http.Request) (interface{}
req := unassignUsersReq{
token: apiutil.ExtractBearerToken(r),
domainID: bone.GetValue(r, "domainID"),
domainID: chi.URLParam(r, "domainID"),
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, errors.Wrap(apiutil.ErrValidation, errors.Wrap(err, errors.ErrMalformedEntity))
@@ -123,7 +123,7 @@ func decodeListUserDomainsRequest(ctx context.Context, r *http.Request) (interfa
}
req := listUserDomainsReq{
token: apiutil.ExtractBearerToken(r),
userID: bone.GetValue(r, "userID"),
userID: chi.URLParam(r, "userID"),
page: page,
}
return req, nil
+59 -58
View File
@@ -8,82 +8,83 @@ import (
"github.com/absmach/magistrala/internal/api"
"github.com/absmach/magistrala/internal/apiutil"
"github.com/absmach/magistrala/logger"
"github.com/go-chi/chi/v5"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/go-zoo/bone"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
func MakeHandler(svc auth.Service, r *bone.Mux, logger logger.Logger) *bone.Mux {
func MakeHandler(svc auth.Service, mux *chi.Mux, logger logger.Logger) *chi.Mux {
opts := []kithttp.ServerOption{
kithttp.ServerErrorEncoder(apiutil.LoggingErrorEncoder(logger, api.EncodeError)),
}
dr := bone.New()
mux.Route("/domains", func(r chi.Router) {
r.Post("/", otelhttp.NewHandler(kithttp.NewServer(
createDomainEndpoint(svc),
decodeCreateDomainRequest,
api.EncodeResponse,
opts...,
), "create_domain").ServeHTTP)
dr.Post("", otelhttp.NewHandler(kithttp.NewServer(
createDomainEndpoint(svc),
decodeCreateDomainRequest,
api.EncodeResponse,
opts...,
), "create_domain"))
r.Get("/", otelhttp.NewHandler(kithttp.NewServer(
listDomainsEndpoint(svc),
decodeListDomainRequest,
api.EncodeResponse,
opts...,
), "list_domains").ServeHTTP)
dr.Get("/:domainID", otelhttp.NewHandler(kithttp.NewServer(
retrieveDomainEndpoint(svc),
decodeRetrieveDomainRequest,
api.EncodeResponse,
opts...,
), "view_domain"))
r.Route("/{domainID}", func(r chi.Router) {
r.Get("/", otelhttp.NewHandler(kithttp.NewServer(
retrieveDomainEndpoint(svc),
decodeRetrieveDomainRequest,
api.EncodeResponse,
opts...,
), "view_domain").ServeHTTP)
dr.Patch("/:domainID", otelhttp.NewHandler(kithttp.NewServer(
updateDomainEndpoint(svc),
decodeUpdateDomainRequest,
api.EncodeResponse,
opts...,
), "update_domain"))
r.Patch("/", otelhttp.NewHandler(kithttp.NewServer(
updateDomainEndpoint(svc),
decodeUpdateDomainRequest,
api.EncodeResponse,
opts...,
), "update_domain").ServeHTTP)
dr.Get("", otelhttp.NewHandler(kithttp.NewServer(
listDomainsEndpoint(svc),
decodeListDomainRequest,
api.EncodeResponse,
opts...,
), "list_domains"))
r.Post("/enable", otelhttp.NewHandler(kithttp.NewServer(
enableDomainEndpoint(svc),
decodeEnableDomainRequest,
api.EncodeResponse,
opts...,
), "enable_domain").ServeHTTP)
dr.Post("/:domainID/enable", otelhttp.NewHandler(kithttp.NewServer(
enableDomainEndpoint(svc),
decodeEnableDomainRequest,
api.EncodeResponse,
opts...,
), "enable_domain"))
r.Post("/disable", otelhttp.NewHandler(kithttp.NewServer(
disableDomainEndpoint(svc),
decodeDisableDomainRequest,
api.EncodeResponse,
opts...,
), "disable_domain").ServeHTTP)
dr.Post("/:domainID/disable", otelhttp.NewHandler(kithttp.NewServer(
disableDomainEndpoint(svc),
decodeDisableDomainRequest,
api.EncodeResponse,
opts...,
), "disable_domain"))
r.Route("/users", func(r chi.Router) {
r.Post("/assign", otelhttp.NewHandler(kithttp.NewServer(
assignDomainUsersEndpoint(svc),
decodeAssignUsersRequest,
api.EncodeResponse,
opts...,
), "assign_domain_users").ServeHTTP)
dr.Post("/:domainID/users/assign", otelhttp.NewHandler(kithttp.NewServer(
assignDomainUsersEndpoint(svc),
decodeAssignUsersRequest,
api.EncodeResponse,
opts...,
), "assign_domain_users"))
dr.Post("/:domainID/users/unassign", otelhttp.NewHandler(kithttp.NewServer(
unassignDomainUsersEndpoint(svc),
decodeUnassignUsersRequest,
api.EncodeResponse,
opts...,
), "unassign_domain_users"))
r.SubRoute("/domains", dr)
r.Get("/users/:userID/domains", otelhttp.NewHandler(kithttp.NewServer(
r.Post("/unassign", otelhttp.NewHandler(kithttp.NewServer(
unassignDomainUsersEndpoint(svc),
decodeUnassignUsersRequest,
api.EncodeResponse,
opts...,
), "unassign_domain_users").ServeHTTP)
})
})
})
mux.Get("/users/{userID}/domains", otelhttp.NewHandler(kithttp.NewServer(
listUserDomainsEndpoint(svc),
decodeListUserDomainsRequest,
api.EncodeResponse,
opts...,
), "list_domains_by_user_id"))
), "list_domains_by_user_id").ServeHTTP)
return r
return mux
}
+23 -22
View File
@@ -14,38 +14,39 @@ import (
"github.com/absmach/magistrala/internal/apiutil"
"github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/pkg/errors"
"github.com/go-chi/chi/v5"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/go-zoo/bone"
)
const contentType = "application/json"
// MakeHandler returns a HTTP handler for API endpoints.
func MakeHandler(svc auth.Service, mux *bone.Mux, logger logger.Logger) *bone.Mux {
func MakeHandler(svc auth.Service, mux *chi.Mux, logger logger.Logger) *chi.Mux {
opts := []kithttp.ServerOption{
kithttp.ServerErrorEncoder(apiutil.LoggingErrorEncoder(logger, encodeError)),
}
mux.Post("/keys", kithttp.NewServer(
issueEndpoint(svc),
decodeIssue,
encodeResponse,
opts...,
))
mux.Route("/keys", func(r chi.Router) {
r.Post("/", kithttp.NewServer(
issueEndpoint(svc),
decodeIssue,
encodeResponse,
opts...,
).ServeHTTP)
mux.Get("/keys/:id", kithttp.NewServer(
(retrieveEndpoint(svc)),
decodeKeyReq,
encodeResponse,
opts...,
))
mux.Delete("/keys/:id", kithttp.NewServer(
(revokeEndpoint(svc)),
decodeKeyReq,
encodeResponse,
opts...,
))
r.Get("/{id}", kithttp.NewServer(
(retrieveEndpoint(svc)),
decodeKeyReq,
encodeResponse,
opts...,
).ServeHTTP)
r.Delete("/{id}", kithttp.NewServer(
(revokeEndpoint(svc)),
decodeKeyReq,
encodeResponse,
opts...,
).ServeHTTP)
})
return mux
}
@@ -65,7 +66,7 @@ func decodeIssue(_ context.Context, r *http.Request) (interface{}, error) {
func decodeKeyReq(_ context.Context, r *http.Request) (interface{}, error) {
req := keyReq{
token: apiutil.ExtractBearerToken(r),
id: bone.GetValue(r, "id"),
id: chi.URLParam(r, "id"),
}
return req, nil
}
+3 -3
View File
@@ -10,18 +10,18 @@ import (
"github.com/absmach/magistrala/auth/api/http/domains"
"github.com/absmach/magistrala/auth/api/http/keys"
"github.com/absmach/magistrala/logger"
"github.com/go-zoo/bone"
"github.com/go-chi/chi/v5"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// MakeHandler returns a HTTP handler for API endpoints.
func MakeHandler(svc auth.Service, logger logger.Logger, instanceID string) http.Handler {
mux := bone.New()
mux := chi.NewRouter()
mux = keys.MakeHandler(svc, mux, logger)
mux = domains.MakeHandler(svc, mux, logger)
mux.GetFunc("/health", magistrala.Health("auth", instanceID))
mux.Get("/health", magistrala.Health("auth", instanceID))
mux.Handle("/metrics", promhttp.Handler())
return mux
+65 -60
View File
@@ -15,8 +15,8 @@ import (
"github.com/absmach/magistrala/internal/apiutil"
mglog "github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/pkg/errors"
"github.com/go-chi/chi/v5"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/go-zoo/bone"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
@@ -39,69 +39,74 @@ func MakeHandler(svc bootstrap.Service, reader bootstrap.ConfigReader, logger mg
opts := []kithttp.ServerOption{
kithttp.ServerErrorEncoder(apiutil.LoggingErrorEncoder(logger, encodeError)),
}
r := bone.New()
r.Post("/things/configs", otelhttp.NewHandler(kithttp.NewServer(
addEndpoint(svc),
decodeAddRequest,
encodeResponse,
opts...), "add"))
r := chi.NewRouter()
r.Get("/things/configs/:configID", otelhttp.NewHandler(kithttp.NewServer(
viewEndpoint(svc),
decodeEntityRequest,
encodeResponse,
opts...), "view"))
r.Route("/things", func(r chi.Router) {
r.Route("/configs", func(r chi.Router) {
r.Post("/", otelhttp.NewHandler(kithttp.NewServer(
addEndpoint(svc),
decodeAddRequest,
encodeResponse,
opts...), "add").ServeHTTP)
r.Put("/things/configs/:configID", otelhttp.NewHandler(kithttp.NewServer(
updateEndpoint(svc),
decodeUpdateRequest,
encodeResponse,
opts...), "update"))
r.Get("/", otelhttp.NewHandler(kithttp.NewServer(
listEndpoint(svc),
decodeListRequest,
encodeResponse,
opts...), "list").ServeHTTP)
r.Patch("/things/configs/certs/:certID", otelhttp.NewHandler(kithttp.NewServer(
updateCertEndpoint(svc),
decodeUpdateCertRequest,
encodeResponse,
opts...), "update_cert"))
r.Get("/{configID}", otelhttp.NewHandler(kithttp.NewServer(
viewEndpoint(svc),
decodeEntityRequest,
encodeResponse,
opts...), "view").ServeHTTP)
r.Put("/things/configs/connections/:connID", otelhttp.NewHandler(kithttp.NewServer(
updateConnEndpoint(svc),
decodeUpdateConnRequest,
encodeResponse,
opts...), "update_connections"))
r.Put("/{configID}", otelhttp.NewHandler(kithttp.NewServer(
updateEndpoint(svc),
decodeUpdateRequest,
encodeResponse,
opts...), "update").ServeHTTP)
r.Get("/things/configs", otelhttp.NewHandler(kithttp.NewServer(
listEndpoint(svc),
decodeListRequest,
encodeResponse,
opts...), "list"))
r.Delete("/{configID}", otelhttp.NewHandler(kithttp.NewServer(
removeEndpoint(svc),
decodeEntityRequest,
encodeResponse,
opts...), "remove").ServeHTTP)
r.Get("/things/bootstrap/:externalID", otelhttp.NewHandler(kithttp.NewServer(
bootstrapEndpoint(svc, reader, false),
decodeBootstrapRequest,
encodeResponse,
opts...), "bootstrap"))
r.Patch("/certs/{certID}", otelhttp.NewHandler(kithttp.NewServer(
updateCertEndpoint(svc),
decodeUpdateCertRequest,
encodeResponse,
opts...), "update_cert").ServeHTTP)
r.Get("/things/bootstrap/secure/:externalID", otelhttp.NewHandler(kithttp.NewServer(
bootstrapEndpoint(svc, reader, true),
decodeBootstrapRequest,
encodeSecureRes,
opts...), "bootstrap_secure"))
r.Put("/connections/{connID}", otelhttp.NewHandler(kithttp.NewServer(
updateConnEndpoint(svc),
decodeUpdateConnRequest,
encodeResponse,
opts...), "update_connections").ServeHTTP)
})
r.Put("/things/state/:thingID", otelhttp.NewHandler(kithttp.NewServer(
stateEndpoint(svc),
decodeStateRequest,
encodeResponse,
opts...), "update_state"))
r.Route("/bootstrap", func(r chi.Router) {
r.Get("/{externalID}", otelhttp.NewHandler(kithttp.NewServer(
bootstrapEndpoint(svc, reader, false),
decodeBootstrapRequest,
encodeResponse,
opts...), "bootstrap").ServeHTTP)
r.Get("/secure/{externalID}", otelhttp.NewHandler(kithttp.NewServer(
bootstrapEndpoint(svc, reader, true),
decodeBootstrapRequest,
encodeSecureRes,
opts...), "bootstrap_secure").ServeHTTP)
})
r.Delete("/things/configs/:configID", otelhttp.NewHandler(kithttp.NewServer(
removeEndpoint(svc),
decodeEntityRequest,
encodeResponse,
opts...), "remove"))
r.GetFunc("/health", magistrala.Health("bootstrap", instanceID))
r.Put("/state/{thingID}", otelhttp.NewHandler(kithttp.NewServer(
stateEndpoint(svc),
decodeStateRequest,
encodeResponse,
opts...), "update_state").ServeHTTP)
})
r.Get("/health", magistrala.Health("bootstrap", instanceID))
r.Handle("/metrics", promhttp.Handler())
return r
@@ -127,7 +132,7 @@ func decodeUpdateRequest(_ context.Context, r *http.Request) (interface{}, error
req := updateReq{
token: apiutil.ExtractBearerToken(r),
id: bone.GetValue(r, "configID"),
id: chi.URLParam(r, "configID"),
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, errors.Wrap(apiutil.ErrValidation, errors.Wrap(err, errors.ErrMalformedEntity))
@@ -143,7 +148,7 @@ func decodeUpdateCertRequest(_ context.Context, r *http.Request) (interface{}, e
req := updateCertReq{
token: apiutil.ExtractBearerToken(r),
thingID: bone.GetValue(r, "certID"),
thingID: chi.URLParam(r, "certID"),
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, errors.Wrap(apiutil.ErrValidation, errors.Wrap(err, errors.ErrMalformedEntity))
@@ -159,7 +164,7 @@ func decodeUpdateConnRequest(_ context.Context, r *http.Request) (interface{}, e
req := updateConnReq{
token: apiutil.ExtractBearerToken(r),
id: bone.GetValue(r, "connID"),
id: chi.URLParam(r, "connID"),
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, errors.Wrap(apiutil.ErrValidation, errors.Wrap(err, errors.ErrMalformedEntity))
@@ -196,7 +201,7 @@ func decodeListRequest(_ context.Context, r *http.Request) (interface{}, error)
func decodeBootstrapRequest(_ context.Context, r *http.Request) (interface{}, error) {
req := bootstrapReq{
id: bone.GetValue(r, "externalID"),
id: chi.URLParam(r, "externalID"),
key: apiutil.ExtractThingKey(r),
}
@@ -210,7 +215,7 @@ func decodeStateRequest(_ context.Context, r *http.Request) (interface{}, error)
req := changeStateReq{
token: apiutil.ExtractBearerToken(r),
id: bone.GetValue(r, "thingID"),
id: chi.URLParam(r, "thingID"),
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, errors.Wrap(apiutil.ErrValidation, errors.Wrap(err, errors.ErrMalformedEntity))
@@ -222,7 +227,7 @@ func decodeStateRequest(_ context.Context, r *http.Request) (interface{}, error)
func decodeEntityRequest(_ context.Context, r *http.Request) (interface{}, error) {
req := entityReq{
token: apiutil.ExtractBearerToken(r),
id: bone.GetValue(r, "configID"),
id: chi.URLParam(r, "configID"),
}
return req, nil
+27 -28
View File
@@ -13,8 +13,8 @@ import (
"github.com/absmach/magistrala/internal/apiutil"
"github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/pkg/errors"
"github.com/go-chi/chi/v5"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/go-zoo/bone"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
@@ -33,38 +33,37 @@ func MakeHandler(svc certs.Service, logger logger.Logger, instanceID string) htt
kithttp.ServerErrorEncoder(apiutil.LoggingErrorEncoder(logger, encodeError)),
}
r := bone.New()
r.Post("/certs", otelhttp.NewHandler(kithttp.NewServer(
issueCert(svc),
decodeCerts,
encodeResponse,
opts...,
), "issue"))
r.Get("/certs/:certID", otelhttp.NewHandler(kithttp.NewServer(
viewCert(svc),
decodeViewCert,
encodeResponse,
opts...,
), "view"))
r.Delete("/certs/:certID", otelhttp.NewHandler(kithttp.NewServer(
revokeCert(svc),
decodeRevokeCerts,
encodeResponse,
opts...,
), "revoke"))
r := chi.NewRouter()
r.Route("/certs", func(r chi.Router) {
r.Post("/", otelhttp.NewHandler(kithttp.NewServer(
issueCert(svc),
decodeCerts,
encodeResponse,
opts...,
), "issue").ServeHTTP)
r.Get("/{certID}", otelhttp.NewHandler(kithttp.NewServer(
viewCert(svc),
decodeViewCert,
encodeResponse,
opts...,
), "view").ServeHTTP)
r.Delete("/{certID}", otelhttp.NewHandler(kithttp.NewServer(
revokeCert(svc),
decodeRevokeCerts,
encodeResponse,
opts...,
), "revoke").ServeHTTP)
})
r.Get("/serials/:thingID", otelhttp.NewHandler(kithttp.NewServer(
listSerials(svc),
decodeListCerts,
encodeResponse,
opts...,
), "list_serials"))
), "list_serials").ServeHTTP)
r.Handle("/metrics", promhttp.Handler())
r.GetFunc("/health", magistrala.Health("certs", instanceID))
r.Get("/health", magistrala.Health("certs", instanceID))
return r
}
@@ -99,7 +98,7 @@ func decodeListCerts(_ context.Context, r *http.Request) (interface{}, error) {
req := listReq{
token: apiutil.ExtractBearerToken(r),
thingID: bone.GetValue(r, "thingID"),
thingID: chi.URLParam(r, "thingID"),
limit: l,
offset: o,
}
@@ -109,7 +108,7 @@ func decodeListCerts(_ context.Context, r *http.Request) (interface{}, error) {
func decodeViewCert(_ context.Context, r *http.Request) (interface{}, error) {
req := viewReq{
token: apiutil.ExtractBearerToken(r),
serialID: bone.GetValue(r, "certID"),
serialID: chi.URLParam(r, "certID"),
}
return req, nil
@@ -131,7 +130,7 @@ func decodeCerts(_ context.Context, r *http.Request) (interface{}, error) {
func decodeRevokeCerts(_ context.Context, r *http.Request) (interface{}, error) {
req := revokeReq{
token: apiutil.ExtractBearerToken(r),
certID: bone.GetValue(r, "certID"),
certID: chi.URLParam(r, "certID"),
}
return req, nil
+3 -3
View File
@@ -18,7 +18,7 @@ import (
mglog "github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/pkg/errors"
"github.com/absmach/magistrala/pkg/messaging"
"github.com/go-zoo/bone"
"github.com/go-chi/chi/v5"
"github.com/plgd-dev/go-coap/v2/message"
"github.com/plgd-dev/go-coap/v2/message/codes"
"github.com/plgd-dev/go-coap/v2/mux"
@@ -50,8 +50,8 @@ var (
// MakeHandler returns a HTTP handler for API endpoints.
func MakeHandler(instanceID string) http.Handler {
b := bone.New()
b.GetFunc("/health", magistrala.Health(protocol, instanceID))
b := chi.NewRouter()
b.Get("/health", magistrala.Health(protocol, instanceID))
b.Handle("/metrics", promhttp.Handler())
return b
+32 -30
View File
@@ -14,8 +14,8 @@ import (
"github.com/absmach/magistrala/internal/apiutil"
"github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/pkg/errors"
"github.com/go-chi/chi/v5"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/go-zoo/bone"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
@@ -36,37 +36,39 @@ func MakeHandler(svc notifiers.Service, logger logger.Logger, instanceID string)
kithttp.ServerErrorEncoder(apiutil.LoggingErrorEncoder(logger, encodeError)),
}
mux := bone.New()
mux := chi.NewRouter()
mux.Post("/subscriptions", otelhttp.NewHandler(kithttp.NewServer(
createSubscriptionEndpoint(svc),
decodeCreate,
encodeResponse,
opts...,
), "create"))
mux.Route("/subscriptions", func(r chi.Router) {
r.Post("/", otelhttp.NewHandler(kithttp.NewServer(
createSubscriptionEndpoint(svc),
decodeCreate,
encodeResponse,
opts...,
), "create").ServeHTTP)
mux.Get("/subscriptions/:subID", otelhttp.NewHandler(kithttp.NewServer(
viewSubscriptionEndpint(svc),
decodeSubscription,
encodeResponse,
opts...,
), "view"))
r.Get("/", otelhttp.NewHandler(kithttp.NewServer(
listSubscriptionsEndpoint(svc),
decodeList,
encodeResponse,
opts...,
), "list").ServeHTTP)
mux.Get("/subscriptions", otelhttp.NewHandler(kithttp.NewServer(
listSubscriptionsEndpoint(svc),
decodeList,
encodeResponse,
opts...,
), "list"))
r.Get("/{subID}", otelhttp.NewHandler(kithttp.NewServer(
viewSubscriptionEndpint(svc),
decodeSubscription,
encodeResponse,
opts...,
), "view").ServeHTTP)
mux.Delete("/subscriptions/:subID", otelhttp.NewHandler(kithttp.NewServer(
deleteSubscriptionEndpint(svc),
decodeSubscription,
encodeResponse,
opts...,
), "delete"))
r.Delete("/{subID}", otelhttp.NewHandler(kithttp.NewServer(
deleteSubscriptionEndpint(svc),
decodeSubscription,
encodeResponse,
opts...,
), "delete").ServeHTTP)
})
mux.GetFunc("/health", magistrala.Health("notifier", instanceID))
mux.Get("/health", magistrala.Health("notifier", instanceID))
mux.Handle("/metrics", promhttp.Handler())
return mux
@@ -87,7 +89,7 @@ func decodeCreate(_ context.Context, r *http.Request) (interface{}, error) {
func decodeSubscription(_ context.Context, r *http.Request) (interface{}, error) {
req := subReq{
id: bone.GetValue(r, "subID"),
id: chi.URLParam(r, "subID"),
token: apiutil.ExtractBearerToken(r),
}
@@ -96,12 +98,12 @@ func decodeSubscription(_ context.Context, r *http.Request) (interface{}, error)
func decodeList(_ context.Context, r *http.Request) (interface{}, error) {
req := listSubsReq{token: apiutil.ExtractBearerToken(r)}
vals := bone.GetQuery(r, topicKey)
vals := r.URL.Query()[topicKey]
if len(vals) > 0 {
req.topic = vals[0]
}
vals = bone.GetQuery(r, contactKey)
vals = r.URL.Query()[contactKey]
if len(vals) > 0 {
req.contact = vals[0]
}
+3 -3
View File
@@ -7,14 +7,14 @@ import (
"net/http"
"github.com/absmach/magistrala"
"github.com/go-zoo/bone"
"github.com/go-chi/chi/v5"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// MakeHandler returns a HTTP API handler with health check and metrics.
func MakeHandler(svcName, instanceID string) http.Handler {
r := bone.New()
r.GetFunc("/health", magistrala.Health(svcName, instanceID))
r := chi.NewRouter()
r.Get("/health", magistrala.Health(svcName, instanceID))
r.Handle("/metrics", promhttp.Handler())
return r
+1
View File
@@ -100,6 +100,7 @@ require (
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect
github.com/gin-gonic/gin v1.9.1 // indirect
github.com/go-chi/chi v1.5.5 // indirect
github.com/go-gorp/gorp/v3 v3.1.0 // indirect
github.com/go-jose/go-jose/v3 v3.0.1 // indirect
github.com/go-logfmt/logfmt v0.6.0 // indirect
+2
View File
@@ -279,6 +279,8 @@ github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SU
github.com/glycerine/go-unsnap-stream v0.0.0-20180323001048-9f0cb55181dd/go.mod h1:/20jfyN9Y5QPEAprSgKAUr+glWDY39ZiUEAYOEv5dsE=
github.com/glycerine/goconvey v0.0.0-20190410193231-58a59202ab31/go.mod h1:Ogl1Tioa0aV7gstGFO7KhffUsb9M4ydbEbbxpcEDc24=
github.com/go-acme/lego v2.7.2+incompatible/go.mod h1:yzMNe9CasVUhkquNvti5nAtPmG94USbYxYrZfTkIn0M=
github.com/go-chi/chi v1.5.5 h1:vOB/HbEMt9QqBqErz07QehcOKHaWFtuj87tTDVz2qXE=
github.com/go-chi/chi v1.5.5/go.mod h1:C9JqLr3tIYjDOZpzn+BCuxY8z8vmca43EeMgyZt7irw=
github.com/go-chi/chi/v5 v5.0.10 h1:rLz5avzKpjqxrYwXNfmjkrYYXOyLJd37pz53UFHC6vk=
github.com/go-chi/chi/v5 v5.0.10/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
+5 -5
View File
@@ -11,8 +11,8 @@ import (
"github.com/absmach/magistrala"
"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"
"github.com/go-zoo/bone"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"google.golang.org/grpc/codes"
@@ -33,22 +33,22 @@ func MakeHandler(instanceID string) http.Handler {
kithttp.ServerErrorEncoder(encodeError),
}
r := bone.New()
r := chi.NewRouter()
r.Post("/channels/:chanID/messages", otelhttp.NewHandler(kithttp.NewServer(
sendMessageEndpoint(),
decodeRequest,
encodeResponse,
opts...,
), "publish"))
), "publish").ServeHTTP)
r.Post("/channels/:chanID/messages/*", otelhttp.NewHandler(kithttp.NewServer(
sendMessageEndpoint(),
decodeRequest,
encodeResponse,
opts...,
), "publish"))
), "publish").ServeHTTP)
r.GetFunc("/health", magistrala.Health("http", instanceID))
r.Get("/health", magistrala.Health("http", instanceID))
r.Handle("/metrics", promhttp.Handler())
return r
+6 -7
View File
@@ -12,7 +12,6 @@ import (
"github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/pkg/errors"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/go-zoo/bone"
)
// LoggingErrorEncoder is a go-kit error encoder logging decorator.
@@ -27,7 +26,7 @@ func LoggingErrorEncoder(logger logger.Logger, enc kithttp.ErrorEncoder) kithttp
// ReadUintQuery reads the value of uint64 http query parameters for a given key.
func ReadUintQuery(r *http.Request, key string, def uint64) (uint64, error) {
vals := bone.GetQuery(r, key)
vals := r.URL.Query()[key]
if len(vals) > 1 {
return 0, ErrInvalidQueryParams
}
@@ -47,7 +46,7 @@ func ReadUintQuery(r *http.Request, key string, def uint64) (uint64, error) {
// ReadStringQuery reads the value of string http query parameters for a given key.
func ReadStringQuery(r *http.Request, key string, def string) (string, error) {
vals := bone.GetQuery(r, key)
vals := r.URL.Query()[key]
if len(vals) > 1 {
return "", ErrInvalidQueryParams
}
@@ -61,7 +60,7 @@ func ReadStringQuery(r *http.Request, key string, def string) (string, error) {
// ReadMetadataQuery reads the value of json http query parameters for a given key.
func ReadMetadataQuery(r *http.Request, key string, def map[string]interface{}) (map[string]interface{}, error) {
vals := bone.GetQuery(r, key)
vals := r.URL.Query()[key]
if len(vals) > 1 {
return nil, ErrInvalidQueryParams
}
@@ -81,7 +80,7 @@ func ReadMetadataQuery(r *http.Request, key string, def map[string]interface{})
// ReadBoolQuery reads boolean query parameters in a given http request.
func ReadBoolQuery(r *http.Request, key string, def bool) (bool, error) {
vals := bone.GetQuery(r, key)
vals := r.URL.Query()[key]
if len(vals) > 1 {
return false, ErrInvalidQueryParams
}
@@ -100,7 +99,7 @@ func ReadBoolQuery(r *http.Request, key string, def bool) (bool, error) {
// ReadFloatQuery reads the value of float64 http query parameters for a given key.
func ReadFloatQuery(r *http.Request, key string, def float64) (float64, error) {
vals := bone.GetQuery(r, key)
vals := r.URL.Query()[key]
if len(vals) > 1 {
return 0, ErrInvalidQueryParams
}
@@ -124,7 +123,7 @@ type number interface {
// ReadNumQuery returns a numeric value.
func ReadNumQuery[N number](r *http.Request, key string, def N) (N, error) {
vals := bone.GetQuery(r, key)
vals := r.URL.Query()[key]
if len(vals) > 1 {
return 0, ErrInvalidQueryParams
}
+3 -3
View File
@@ -7,14 +7,14 @@ import (
"net/http"
"github.com/absmach/magistrala"
"github.com/go-zoo/bone"
"github.com/go-chi/chi/v5"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
// MakeHandler returns a HTTP handler for API endpoints.
func MakeHandler(instanceID string) http.Handler {
r := bone.New()
r.GetFunc("/health", magistrala.Health("lora-adapter", instanceID))
r := chi.NewRouter()
r.Get("/health", magistrala.Health("lora-adapter", instanceID))
r.Handle("/metrics", promhttp.Handler())
return r
+4 -4
View File
@@ -13,8 +13,8 @@ import (
mglog "github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/opcua"
"github.com/absmach/magistrala/pkg/errors"
"github.com/go-chi/chi/v5"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/go-zoo/bone"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
@@ -33,16 +33,16 @@ func MakeHandler(svc opcua.Service, logger mglog.Logger, instanceID string) http
kithttp.ServerErrorEncoder(apiutil.LoggingErrorEncoder(logger, encodeError)),
}
r := bone.New()
r := chi.NewRouter()
r.Get("/browse", kithttp.NewServer(
browseEndpoint(svc),
decodeBrowse,
encodeResponse,
opts...,
))
).ServeHTTP)
r.GetFunc("/health", magistrala.Health("opcua-adapter", instanceID))
r.Get("/health", magistrala.Health("opcua-adapter", instanceID))
r.Handle("/metrics", promhttp.Handler())
return r
+5 -5
View File
@@ -13,8 +13,8 @@ import (
"github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/pkg/errors"
"github.com/absmach/magistrala/provision"
"github.com/go-chi/chi/v5"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/go-zoo/bone"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
@@ -28,24 +28,24 @@ func MakeHandler(svc provision.Service, logger logger.Logger, instanceID string)
kithttp.ServerErrorEncoder(apiutil.LoggingErrorEncoder(logger, encodeError)),
}
r := bone.New()
r := chi.NewRouter()
r.Post("/mapping", kithttp.NewServer(
doProvision(svc),
decodeProvisionRequest,
encodeResponse,
opts...,
))
).ServeHTTP)
r.Get("/mapping", kithttp.NewServer(
getMapping(svc),
decodeMappingRequest,
encodeResponse,
opts...,
))
).ServeHTTP)
r.Handle("/metrics", promhttp.Handler())
r.GetFunc("/health", magistrala.Health("provision", instanceID))
r.Get("/health", magistrala.Health("provision", instanceID))
return r
}
+5 -5
View File
@@ -12,8 +12,8 @@ import (
"github.com/absmach/magistrala/internal/apiutil"
"github.com/absmach/magistrala/pkg/errors"
"github.com/absmach/magistrala/readers"
"github.com/go-chi/chi/v5"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/go-zoo/bone"
"github.com/prometheus/client_golang/prometheus/promhttp"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
@@ -54,15 +54,15 @@ func MakeHandler(svc readers.MessageRepository, uauth magistrala.AuthServiceClie
kithttp.ServerErrorEncoder(encodeError),
}
mux := bone.New()
mux := chi.NewRouter()
mux.Get("/channels/:chanID/messages", kithttp.NewServer(
listMessagesEndpoint(svc, uauth, taauth),
decodeList,
encodeResponse,
opts...,
))
).ServeHTTP)
mux.GetFunc("/health", magistrala.Health(svcName, instanceID))
mux.Get("/health", magistrala.Health(svcName, instanceID))
mux.Handle("/metrics", promhttp.Handler())
return mux
@@ -140,7 +140,7 @@ func decodeList(_ context.Context, r *http.Request) (interface{}, error) {
}
req := listMessagesReq{
chanID: bone.GetValue(r, "chanID"),
chanID: chi.URLParam(r, "chanID"),
token: apiutil.ExtractBearerToken(r),
key: apiutil.ExtractThingKey(r),
pageMeta: readers.PageMetadata{
+40 -43
View File
@@ -14,8 +14,8 @@ import (
"github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/pkg/errors"
"github.com/absmach/magistrala/twins"
"github.com/go-chi/chi/v5"
kithttp "github.com/go-kit/kit/transport/http"
"github.com/go-zoo/bone"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
@@ -36,51 +36,48 @@ func MakeHandler(svc twins.Service, logger logger.Logger, instanceID string) htt
kithttp.ServerErrorEncoder(apiutil.LoggingErrorEncoder(logger, encodeError)),
}
r := bone.New()
r := chi.NewRouter()
r.Post("/twins", otelhttp.NewHandler(kithttp.NewServer(
addTwinEndpoint(svc),
decodeTwinCreation,
encodeResponse,
opts...,
), "add_twin"))
r.Put("/twins/:twinID", otelhttp.NewHandler(kithttp.NewServer(
updateTwinEndpoint(svc),
decodeTwinUpdate,
encodeResponse,
opts...,
), "update_twin"))
r.Get("/twins/:twinID", otelhttp.NewHandler(kithttp.NewServer(
viewTwinEndpoint(svc),
decodeView,
encodeResponse,
opts...,
), "view_twin"))
r.Delete("/twins/:twinID", otelhttp.NewHandler(kithttp.NewServer(
removeTwinEndpoint(svc),
decodeView,
encodeResponse,
opts...,
), "remove_twin"))
r.Get("/twins", otelhttp.NewHandler(kithttp.NewServer(
listTwinsEndpoint(svc),
decodeList,
encodeResponse,
opts...,
), "list_twins"))
r.Get("/states/:twinID", otelhttp.NewHandler(kithttp.NewServer(
r.Route("/twins", func(r chi.Router) {
r.Post("/", otelhttp.NewHandler(kithttp.NewServer(
addTwinEndpoint(svc),
decodeTwinCreation,
encodeResponse,
opts...,
), "add_twin").ServeHTTP)
r.Get("/", otelhttp.NewHandler(kithttp.NewServer(
listTwinsEndpoint(svc),
decodeList,
encodeResponse,
opts...,
), "list_twins").ServeHTTP)
r.Put("/{twinID}", otelhttp.NewHandler(kithttp.NewServer(
updateTwinEndpoint(svc),
decodeTwinUpdate,
encodeResponse,
opts...,
), "update_twin").ServeHTTP)
r.Get("/{twinID}", otelhttp.NewHandler(kithttp.NewServer(
viewTwinEndpoint(svc),
decodeView,
encodeResponse,
opts...,
), "view_twin").ServeHTTP)
r.Delete("/{twinID}", otelhttp.NewHandler(kithttp.NewServer(
removeTwinEndpoint(svc),
decodeView,
encodeResponse,
opts...,
), "remove_twin").ServeHTTP)
})
r.Get("/states/{twinID}", otelhttp.NewHandler(kithttp.NewServer(
listStatesEndpoint(svc),
decodeListStates,
encodeResponse,
opts...,
), "list_states"))
), "list_states").ServeHTTP)
r.GetFunc("/health", magistrala.Health("twins", instanceID))
r.Get("/health", magistrala.Health("twins", instanceID))
r.Handle("/metrics", promhttp.Handler())
return r
@@ -106,7 +103,7 @@ func decodeTwinUpdate(_ context.Context, r *http.Request) (interface{}, error) {
req := updateTwinReq{
token: apiutil.ExtractBearerToken(r),
id: bone.GetValue(r, "twinID"),
id: chi.URLParam(r, "twinID"),
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return nil, errors.Wrap(apiutil.ErrValidation, errors.Wrap(err, errors.ErrMalformedEntity))
@@ -118,7 +115,7 @@ func decodeTwinUpdate(_ context.Context, r *http.Request) (interface{}, error) {
func decodeView(_ context.Context, r *http.Request) (interface{}, error) {
req := viewTwinReq{
token: apiutil.ExtractBearerToken(r),
id: bone.GetValue(r, "twinID"),
id: chi.URLParam(r, "twinID"),
}
return req, nil
@@ -171,7 +168,7 @@ func decodeListStates(_ context.Context, r *http.Request) (interface{}, error) {
token: apiutil.ExtractBearerToken(r),
limit: l,
offset: o,
id: bone.GetValue(r, "twinID"),
id: chi.URLParam(r, "twinID"),
}
return req, nil
+3 -3
View File
@@ -13,7 +13,7 @@ import (
"github.com/absmach/magistrala/pkg/errors"
"github.com/absmach/magistrala/ws"
"github.com/go-zoo/bone"
"github.com/go-chi/chi/v5"
)
var channelPartRegExp = regexp.MustCompile(`^/channels/([\w\-]+)/messages(/[^?]*)?(\?.*)?$`)
@@ -45,7 +45,7 @@ func handshake(ctx context.Context, svc ws.Service) http.HandlerFunc {
func decodeRequest(r *http.Request) (connReq, error) {
authKey := r.Header.Get("Authorization")
if authKey == "" {
authKeys := bone.GetQuery(r, "authorization")
authKeys := r.URL.Query()["authorization"]
if len(authKeys) == 0 {
logger.Debug("Missing authorization key.")
return connReq{}, errUnauthorizedAccess
@@ -53,7 +53,7 @@ func decodeRequest(r *http.Request) (connReq, error) {
authKey = authKeys[0]
}
chanID := bone.GetValue(r, "chanID")
chanID := chi.URLParam(r, "chanID")
req := connReq{
thingKey: authKey,
+5 -5
View File
@@ -11,7 +11,7 @@ import (
"github.com/absmach/magistrala"
mglog "github.com/absmach/magistrala/logger"
"github.com/absmach/magistrala/ws"
"github.com/go-zoo/bone"
"github.com/go-chi/chi/v5"
"github.com/gorilla/websocket"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
@@ -39,11 +39,11 @@ var (
func MakeHandler(ctx context.Context, svc ws.Service, l mglog.Logger, instanceID string) http.Handler {
logger = l
mux := bone.New()
mux.GetFunc("/channels/:chanID/messages", handshake(ctx, svc))
mux.GetFunc("/channels/:chanID/messages/*", handshake(ctx, svc))
mux := chi.NewRouter()
mux.Get("/channels/{chanID}/messages", handshake(ctx, svc))
mux.Get("/channels/{chanID}/messages/*", handshake(ctx, svc))
mux.GetFunc("/health", magistrala.Health(service, instanceID))
mux.Get("/health", magistrala.Health(service, instanceID))
mux.Handle("/metrics", promhttp.Handler())
return mux