From 961355caa82f30c0c7283a6a016472d1cd42ff38 Mon Sep 17 00:00:00 2001 From: nicerobot Date: Sun, 24 Jul 2016 16:56:10 -0700 Subject: [PATCH] +routing --- vendor/application/routes.go | 106 ++++++++++++++++++ vendor/application/start.go | 69 +++--------- .../vendor/middleware/logging/logging.go | 23 +++- .../vendor/service/testing/testing.go | 81 ++++++++++++- .../vendor/transport/http/caching/caching.go | 15 ++- .../application/vendor/transport/http/http.go | 8 +- 6 files changed, 235 insertions(+), 67 deletions(-) create mode 100644 vendor/application/routes.go diff --git a/vendor/application/routes.go b/vendor/application/routes.go new file mode 100644 index 0000000..51a9931 --- /dev/null +++ b/vendor/application/routes.go @@ -0,0 +1,106 @@ +package application + +import ( + "middleware/logging" + "service/login" + "service/testing" + "transport/http/caching" + "transport/http/content" + "transport/http/server" + + "github.com/gorilla/mux" + + httptransport "github.com/go-kit/kit/transport/http" + + "golang.org/x/net/context" +) + +// +func routeServices() *mux.Router { + r := mux.NewRouter() + ctx := context.Background() + + // Login + + routeLoginService(ctx, r.PathPrefix("/login").Subrouter().StrictSlash(true)) + + // Testing + + routeTestService(ctx, r.PathPrefix("/test").Subrouter().StrictSlash(true)) + + return r +} + +// +func routeLoginService(ctx context.Context, r *mux.Router) { + + logged := logging.New("login").Middleware() + servered := server.New("opinionated/auth", "gomatic/opinionated/auth") + json := content.New("application/json") + + loginService := login.New() + + // POST / + + r.Methods("POST").Path("/").Handler(httptransport.NewServer( + ctx, + logged(loginService.Endpoint()), + loginService.Decoder, + servered(json(loginService.Encoder)), + )).Name("POST") + +} + +// +func routeTestService(ctx context.Context, r *mux.Router) { + + logged := logging.New("test").Middleware() + servered := server.New("opinionated", "gomatic/opinionated") + json := content.New("application/json") + + testService := testing.New() + + // POST / + // GET /:id + // PUT /:id + // PATCH /:id + // DELETE /:id + + r.Methods("POST").Path("/").Handler(httptransport.NewServer( + ctx, + logged(testService.Post()), + testService.DecodePost, + servered(json(testService.EncodePost)), + )).Name("POST") + r.Methods("POST").Path("/{id}").Handler(httptransport.NewServer( + ctx, + logged(testService.Get()), + testService.DecodeGet, + servered(json(testService.EncodeGet)), + )).Name("POST Id") + r.Methods("GET").Path("/{id}").Handler(caching.New(-1, httptransport.NewServer( + ctx, + logged(testService.Get()), + testService.DecodeGet, + servered(json(testService.EncodeGet)), + ))).Name("GET Id") + r.Methods("PUT").Path("/{id}").Handler(caching.New(-1, httptransport.NewServer( + ctx, + logged(testService.Put()), + testService.DecodePut, + servered(json(testService.EncodePut)), + ))).Name("PUT Id") + r.Methods("PATCH").Path("/{id}").Handler(httptransport.NewServer( + ctx, + logged(testService.Patch()), + testService.DecodePatch, + servered(json(testService.EncodePatch)), + )).Name("PATCH Id") + r.Methods("DELETE").Path("/{id}").Handler(caching.New(-1, httptransport.NewServer( + ctx, + logged(testService.Delete()), + testService.DecodeDelete, + servered(json(testService.EncodeDelete)), + ))).Name("DELETE Id") + +} diff --git a/vendor/application/start.go b/vendor/application/start.go index f0ad99f..29e1952 100644 --- a/vendor/application/start.go +++ b/vendor/application/start.go @@ -7,86 +7,45 @@ import ( "net/http" "strconv" "time" - - "middleware/logging" - "service/login" - "service/testing" - "transport/http/caching" - "transport/http/content" - "transport/http/server" - - httptransport "github.com/go-kit/kit/transport/http" - "golang.org/x/net/context" ) // func Start() error { // Serve public/ - go func() { - static := strconv.Itoa(Settings.Port + 1) - fmt.Println("files on " + static) - http.ListenAndServe(":"+static, http.FileServer(http.Dir("public/"))) - }() - - mux := http.NewServeMux() - ctx := context.Background() // Configure endpoints - // Login - - loginService := login.New() - loggedLogin := logging.New(nil)(loginService.Endpoint()) - - loginEncoder := server.New("opinionated", "gomatic/opinionated")(loginService.Encoder) - loginEncoder = content.New("application/json")(loginEncoder) - - loginHandler := httptransport.NewServer( - ctx, - loggedLogin, - loginService.Decoder, - loginEncoder, - ) - - mux.Handle("/login", loginHandler) - - // Testing + mux := routeServices() - testService := testing.New() - loggedTest := logging.New(nil)(testService.Endpoint()) - - testEncoder := server.New("opinionated", "gomatic/opinionated")(testService.Encoder) - testEncoder = content.New("application/json")(testEncoder) - - testHandler := httptransport.NewServer( - ctx, - loggedTest, - testService.Decoder, - testEncoder, - ) - - mux.Handle("/", caching.New(testHandler)) + mux.Handle("/", http.FileServer(http.Dir("public/"))) // Start the server port := strconv.Itoa(Settings.Port) srv := &http.Server{ - Addr: ":" + port, + Addr: "localhost:" + port, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, Handler: mux, } - if cer, err := tls.LoadX509KeyPair("server.crt", "server.key"); err != nil { + fmt.Println("listening on " + port) + + if cert, err := tls.LoadX509KeyPair("server.crt", "server.key"); err != nil { stderr.Println(err) + return srv.ListenAndServe() + } else { - srv.TLSConfig = &tls.Config{Certificates: []tls.Certificate{cer}} + srv.TLSConfig = &tls.Config{ + Certificates: []tls.Certificate{ + cert, + }, + } + return srv.ListenAndServeTLS("server.crt", "server.key") } - fmt.Println("listening on " + port) - return srv.ListenAndServe() } diff --git a/vendor/application/vendor/middleware/logging/logging.go b/vendor/application/vendor/middleware/logging/logging.go index 13a8c73..f44854a 100644 --- a/vendor/application/vendor/middleware/logging/logging.go +++ b/vendor/application/vendor/middleware/logging/logging.go @@ -10,13 +10,28 @@ import ( ) // -func New(logger log.Logger) endpoint.Middleware { - if logger == nil { - logger = log.NewLogfmtLogger(os.Stderr) +type logger struct { + *log.Context +} + +// +func New(name string) *logger { + l := log.NewLogfmtLogger(os.Stderr) + c := log.NewContext(l).With("time", log.DefaultTimestampUTC) + if name != "" { + c = c.With("service", name) + } + return &logger{c} +} + +// +func (l *logger) Middleware() endpoint.Middleware { + if l == nil { + l = New("") } - logger = log.NewContext(logger).With("time", log.DefaultTimestampUTC) return func(next endpoint.Endpoint) endpoint.Endpoint { + logger := log.Logger(l.Context) return func(ctx context.Context, request interface{}) (interface{}, error) { logger.Log("msg", "calling endpoint", next) defer logger.Log("msg", "called endpoint") diff --git a/vendor/application/vendor/service/testing/testing.go b/vendor/application/vendor/service/testing/testing.go index 6d9097b..3010edb 100644 --- a/vendor/application/vendor/service/testing/testing.go +++ b/vendor/application/vendor/service/testing/testing.go @@ -64,15 +64,88 @@ func New() testEndpoint { } } -// Convenience to get a go-kit type back of test's private endpoint type. -func (e testEndpoint) Endpoint() endpoint.Endpoint { +// +func (e testEndpoint) Post() endpoint.Endpoint { + return endpoint.Endpoint(e) +} + +// +func (e testEndpoint) Get() endpoint.Endpoint { + return endpoint.Endpoint(e) +} + +// +func (e testEndpoint) Put() endpoint.Endpoint { + return endpoint.Endpoint(e) +} + +// +func (e testEndpoint) Patch() endpoint.Endpoint { + return endpoint.Endpoint(e) +} + +// +func (e testEndpoint) Delete() endpoint.Endpoint { return endpoint.Endpoint(e) } // Request/response encoding and decoding. +// POST +func (e testEndpoint) DecodePost(_ context.Context, r *http.Request) (interface{}, error) { + var request testRequest + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + return nil, err + } + return request, nil +} + // -func (e testEndpoint) Decoder(_ context.Context, r *http.Request) (interface{}, error) { +func (e testEndpoint) EncodePost(_ context.Context, w http.ResponseWriter, response interface{}) error { + return json.NewEncoder(w).Encode(response) +} + +// GET +func (e testEndpoint) DecodeGet(_ context.Context, r *http.Request) (interface{}, error) { + var request testRequest + return request, nil +} + +// +func (e testEndpoint) EncodeGet(_ context.Context, w http.ResponseWriter, response interface{}) error { + return json.NewEncoder(w).Encode(response) +} + +// PUT +func (e testEndpoint) DecodePut(_ context.Context, r *http.Request) (interface{}, error) { + var request testRequest + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + return nil, err + } + return request, nil +} + +// +func (e testEndpoint) EncodePut(_ context.Context, w http.ResponseWriter, response interface{}) error { + return json.NewEncoder(w).Encode(response) +} + +// PATCH +func (e testEndpoint) DecodePatch(_ context.Context, r *http.Request) (interface{}, error) { + var request testRequest + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + return nil, err + } + return request, nil +} + +// +func (e testEndpoint) EncodePatch(_ context.Context, w http.ResponseWriter, response interface{}) error { + return json.NewEncoder(w).Encode(response) +} + +// DELETE +func (e testEndpoint) DecodeDelete(_ context.Context, r *http.Request) (interface{}, error) { var request testRequest if err := json.NewDecoder(r.Body).Decode(&request); err != nil { return nil, err @@ -81,6 +154,6 @@ func (e testEndpoint) Decoder(_ context.Context, r *http.Request) (interface{}, } // -func (e testEndpoint) Encoder(_ context.Context, w http.ResponseWriter, response interface{}) error { +func (e testEndpoint) EncodeDelete(_ context.Context, w http.ResponseWriter, response interface{}) error { return json.NewEncoder(w).Encode(response) } diff --git a/vendor/application/vendor/transport/http/caching/caching.go b/vendor/application/vendor/transport/http/caching/caching.go index 9ff50fe..5f16b63 100644 --- a/vendor/application/vendor/transport/http/caching/caching.go +++ b/vendor/application/vendor/transport/http/caching/caching.go @@ -11,6 +11,7 @@ import ( type cached struct { next http.Handler + maxAge int options []string } @@ -19,6 +20,10 @@ func (c cached) ServeHTTP(w http.ResponseWriter, req *http.Request) { now := time.Now() utc := now.UTC() tomorrow := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()).AddDate(0, 0, 1) + age := c.maxAge + if age <= 0 { + age = int(tomorrow.Sub(now).Seconds()) + } nows := fmt.Sprintf("%8x", utc.UnixNano()) rnds := fmt.Sprintf("%8x", rand.Int63()) @@ -52,13 +57,17 @@ func (c cached) ServeHTTP(w http.ResponseWriter, req *http.Request) { hs.Set("Pragma", "no-cache") hs.Set("Expires", "0") } else { - hs.Set("Cache-Control", fmt.Sprintf("public, max-age=%v", int(tomorrow.Sub(now).Seconds()))) + hs.Set("Cache-Control", fmt.Sprintf("public, max-age=%v", age)) } c.next.ServeHTTP(w, req) } // -func New(server http.Handler, options ...string) http.Handler { - return cached{server, options} +func New(maxAge int, server http.Handler, options ...string) http.Handler { + return cached{ + next: server, + maxAge: maxAge, + options: options, + } } diff --git a/vendor/application/vendor/transport/http/http.go b/vendor/application/vendor/transport/http/http.go index 887a582..062ff68 100644 --- a/vendor/application/vendor/transport/http/http.go +++ b/vendor/application/vendor/transport/http/http.go @@ -1,9 +1,15 @@ package http -import httptransport "github.com/go-kit/kit/transport/http" +import ( + httptransport "github.com/go-kit/kit/transport/http" + "github.com/gorilla/mux" +) // type ChainResponseEncoders func(next httptransport.EncodeResponseFunc) httptransport.EncodeResponseFunc // type ChainRequestDecoders func(next httptransport.DecodeRequestFunc) httptransport.DecodeRequestFunc + +// +type ChainRouter func(next *mux.Router) *mux.Router