Skip to content

Commit

Permalink
+routing
Browse files Browse the repository at this point in the history
  • Loading branch information
nicerobot committed Jul 24, 2016
1 parent 988ff8d commit 961355c
Show file tree
Hide file tree
Showing 6 changed files with 235 additions and 67 deletions.
106 changes: 106 additions & 0 deletions vendor/application/routes.go
Original file line number Diff line number Diff line change
@@ -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")

}
69 changes: 14 additions & 55 deletions vendor/application/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
23 changes: 19 additions & 4 deletions vendor/application/vendor/middleware/logging/logging.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
81 changes: 77 additions & 4 deletions vendor/application/vendor/service/testing/testing.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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)
}
15 changes: 12 additions & 3 deletions vendor/application/vendor/transport/http/caching/caching.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (

type cached struct {
next http.Handler
maxAge int
options []string
}

Expand All @@ -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())
Expand Down Expand Up @@ -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,
}
}
8 changes: 7 additions & 1 deletion vendor/application/vendor/transport/http/http.go
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 961355c

Please sign in to comment.