Skip to content

Commit

Permalink
Add category alexandria HTTP server
Browse files Browse the repository at this point in the history
  • Loading branch information
maestre3d committed Jul 22, 2020
1 parent 188d7b5 commit d6cfc99
Show file tree
Hide file tree
Showing 10 changed files with 367 additions and 19 deletions.
70 changes: 70 additions & 0 deletions category-service/cmd/alexandria-server/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package main

import (
"context"
"fmt"
"github.com/maestre3d/alexandria/category-service/pkg/dep"
"github.com/oklog/run"
"log"
"net"
"net/http"
"os"
"os/signal"
"syscall"
)

func main() {
ctx, _ := context.WithCancel(context.Background())
dep.SetContext(ctx)

proxy, cleanup, err := dep.InjectTransportProxy()
if err != nil {
log.Fatal(err)
}
defer func() {
log.Print("stopping services")
cleanup()
}()

var g run.Group
{
l, err := net.Listen("tcp", proxy.HTTP.Server.Addr)
if err != nil {
log.Fatal(err)
}

g.Add(func() error {
log.Print("starting http server")
return http.Serve(l, proxy.HTTP.Server.Handler)
}, func(err error) {
if err != nil {
log.Print(err)
}
log.Print(l.Close())
})
}
{
// Set up signal bind
var (
cancelInterrupt = make(chan struct{})
c = make(chan os.Signal, 2)
)
defer close(c)

g.Add(func() error {
signal.Notify(c, syscall.SIGINT, syscall.SIGTERM)
select {
case sig := <-c:
return fmt.Errorf("received signal %s", sig)
case <-cancelInterrupt:
return nil
}
}, func(error) {
// Cancel root context, propagate cancellation
// cancel()
close(cancelInterrupt)
})
}

log.Fatal(g.Run())
}
4 changes: 2 additions & 2 deletions category-service/config/alexandria-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ alexandria:
tracing:
# OpenTracing/OpenCensus consumers
zipkin:
host: "http://zipkin:9411/api/v2/spans"
endpoint: "0.0.0.0:8081"
host: "http://localhost:9411/api/v2/spans"
endpoint: "0.0.0.0:8080"
bridge: true
eventbus:
kafka:
Expand Down
5 changes: 2 additions & 3 deletions category-service/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,13 @@ require (
github.com/gocql/gocql v0.0.0-20200624222514-34081eda590e
github.com/google/uuid v1.1.1
github.com/google/wire v0.3.0
github.com/gorilla/handlers v1.4.2 // indirect
github.com/gorilla/handlers v1.4.2
github.com/gorilla/mux v1.7.3
github.com/matoous/go-nanoid v1.4.1
github.com/oklog/run v1.1.0 // indirect
github.com/openzipkin/zipkin-go v0.2.2
github.com/prometheus/client_golang v1.3.0
github.com/sony/gobreaker v0.4.1
github.com/spf13/viper v1.6.3
github.com/uber-go/ratelimit v0.1.0 // indirect
go.opencensus.io v0.22.3
go.uber.org/ratelimit v0.1.0
gocloud.dev v0.19.0
Expand Down
5 changes: 0 additions & 5 deletions category-service/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,6 @@ github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuy
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4 h1:Hs82Z41s6SdL1CELW+XaDYmOH4hkBN4/N9og/AsOv7E=
github.com/alecthomas/units v0.0.0-20190717042225-c3de453c63f4/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/alexandria-oss/core v0.2.2 h1:JswkMae7h7majucnWgx/nVs9qWOo3y0+wMqdUNLAocg=
github.com/alexandria-oss/core v0.2.2/go.mod h1:tGEE5LJtgJwf2wecS4ykDlMbshh3LHXKzt7YzAyupCQ=
github.com/alexandria-oss/core v0.5.4-beta h1:m+RU9BbiiFjkbs66F0iQflCu9J/Rv3iYLKblVCJ7XfE=
github.com/alexandria-oss/core v0.5.4-beta/go.mod h1:cAiGx3Kl2132FY1VC0zUHnV7z1C3Z+1ZO1ZiERb/ScY=
github.com/apache/thrift v0.12.0/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ=
Expand Down Expand Up @@ -146,7 +144,6 @@ github.com/go-playground/locales v0.13.0 h1:HyWk6mgj5qFqCT5fjGBuRArbVDfE4hi8+e8c
github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8=
github.com/go-playground/universal-translator v0.17.0 h1:icxd5fm+REJzpZx7ZfpaD876Lmtgy7VtROAbHHXk8no=
github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA=
github.com/go-playground/validator v9.31.0+incompatible h1:UA72EPEogEnq76ehGdEDp4Mit+3FDh548oRqwVgNsHA=
github.com/go-playground/validator/v10 v10.3.0 h1:nZU+7q+yJoFmwvNgv/LnPUkwPal62+b2xXj0AU1Es7o=
github.com/go-playground/validator/v10 v10.3.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI=
github.com/go-redis/redis/v7 v7.2.0 h1:CrCexy/jYWZjW0AyVoHlcJUeZN19VWlbepTh1Vq6dJs=
Expand Down Expand Up @@ -452,8 +449,6 @@ github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/uber-go/ratelimit v0.1.0 h1:ifNbER21JK16BQnK098G8WVgWzdPM9xbyj4kHnRz8g0=
github.com/uber-go/ratelimit v0.1.0/go.mod h1:lH2gBOWIlktoPMmypINnWYWs/lGqSs5k4/3krxDCriY=
github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
github.com/xdg/scram v0.0.0-20180814205039-7eeb5667e42c/go.mod h1:lB8K/P019DLNhemzwFU4jHLhdvlE6uDZjXFejJXr49I=
Expand Down
2 changes: 1 addition & 1 deletion category-service/internal/domain/category_entity.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import (
// Root/Default entity

type Category struct {
ID string
ID string `json:"-"`
ExternalID string `json:"id"`
Name string `json:"name" validate:"required,min=1,max=255"`
CreateTime time.Time `json:"create_time"`
Expand Down
59 changes: 59 additions & 0 deletions category-service/pkg/dep/wire.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
//+build wireinject

package dep

import (
"context"
"github.com/alexandria-oss/core/config"
"github.com/alexandria-oss/core/logger"
"github.com/go-kit/kit/log"
"github.com/google/wire"
"github.com/maestre3d/alexandria/category-service/internal/dependency"
"github.com/maestre3d/alexandria/category-service/pkg/middleware"
"github.com/maestre3d/alexandria/category-service/pkg/service"
"github.com/maestre3d/alexandria/category-service/pkg/transport"
"github.com/maestre3d/alexandria/category-service/pkg/transport/handler"
)

var ctx = context.Background()

var httpCategorySet = wire.NewSet(
provideContext,
logger.NewZapLogger,
provideCategoryService,
handler.NewCategoryHTTP,
)

var transportProxySet = wire.NewSet(
httpCategorySet,
provideHandlers,
config.NewKernel,
transport.NewHTTPServer,
transport.NewProxy,
)

func SetContext(rootCtx context.Context) {
ctx = rootCtx
}

func provideContext() context.Context {
return ctx
}

func provideCategoryService(ctx context.Context, logger log.Logger) (service.Category, func(), error) {
dependency.SetContext(ctx)

useCase, cleanup, err := dependency.InjectCategoryUseCase()
svc := middleware.WrapCategoryMiddleware(useCase, logger)

return svc, cleanup, err
}

func provideHandlers(category *handler.CategoryHTTP) []transport.Handler {
return []transport.Handler{category}
}

func InjectTransportProxy() (*transport.Proxy, func(), error) {
wire.Build(transportProxySet)
return &transport.Proxy{}, nil, nil
}
75 changes: 75 additions & 0 deletions category-service/pkg/dep/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 24 additions & 8 deletions category-service/pkg/transport/handler/category_http.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package transport
package handler

import (
"encoding/json"
Expand All @@ -21,12 +21,16 @@ func NewCategoryHTTP(svc service.Category) *CategoryHTTP {
}
}

func (t *CategoryHTTP) SetRoutes(public, private, admin *mux.Router) {
func (t CategoryHTTP) GetName() string {
return "category"
}

func (t CategoryHTTP) SetRoutes(public, private, admin *mux.Router) {
// Using OpenCensus middleware for distributed tracing
public.Path("/category").Methods(http.MethodGet).Handler(observability.Trace(t.list, true))
public.Path("/category/{id}").Methods(http.MethodGet).Handler(observability.Trace(t.get, true))

private.Path("/category").Methods(http.MethodPost).Handler(observability.Trace(t.create, false))
private.StrictSlash(false).Path("/category").Methods(http.MethodPost).Handler(observability.Trace(t.create, false))
private.Path("/category/{id}").Methods(http.MethodPatch, http.MethodPut).Handler(observability.Trace(t.update, false))
private.Path("/category/{id}").Methods(http.MethodDelete).Handler(observability.Trace(t.delete, false))

Expand All @@ -37,13 +41,17 @@ func (t *CategoryHTTP) SetRoutes(public, private, admin *mux.Router) {
func (t *CategoryHTTP) create(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")

category, err := t.svc.Create(r.Context(), r.PostForm.Get("name"))
category, err := t.svc.Create(r.Context(), r.PostFormValue("name"))
if err != nil {
httputil.ResponseErrJSON(r.Context(), err, w)
return
}

_ = json.NewEncoder(w).Encode(category)
_ = json.NewEncoder(w).Encode(&struct {
Category *domain.Category `json:"category"`
}{
Category: category,
})
}

func (t *CategoryHTTP) get(w http.ResponseWriter, r *http.Request) {
Expand All @@ -55,7 +63,11 @@ func (t *CategoryHTTP) get(w http.ResponseWriter, r *http.Request) {
return
}

_ = json.NewEncoder(w).Encode(category)
_ = json.NewEncoder(w).Encode(&struct {
Category *domain.Category `json:"category"`
}{
Category: category,
})
}

func (t *CategoryHTTP) list(w http.ResponseWriter, r *http.Request) {
Expand Down Expand Up @@ -84,13 +96,17 @@ func (t *CategoryHTTP) list(w http.ResponseWriter, r *http.Request) {
func (t *CategoryHTTP) update(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")

category, err := t.svc.Update(r.Context(), mux.Vars(r)["id"], r.PostForm.Get("name"))
category, err := t.svc.Update(r.Context(), mux.Vars(r)["id"], r.PostFormValue("name"))
if err != nil {
httputil.ResponseErrJSON(r.Context(), err, w)
return
}

_ = json.NewEncoder(w).Encode(category)
_ = json.NewEncoder(w).Encode(&struct {
Category *domain.Category `json:"category"`
}{
Category: category,
})
}

func (t *CategoryHTTP) delete(w http.ResponseWriter, r *http.Request) {
Expand Down
Loading

0 comments on commit d6cfc99

Please sign in to comment.