add simple json endpoint example
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing

This commit is contained in:
2020-10-05 06:15:32 -07:00
parent a26c0b2b47
commit a9887634ab
5 changed files with 49 additions and 2 deletions

15
httpserver/handlers.go Normal file
View File

@@ -0,0 +1,15 @@
package httpserver
import (
"net/http"
"time"
)
func (s *server) handleNow() http.HandlerFunc {
type response struct {
Now time.Time `json:"now"`
}
return func(w http.ResponseWriter, r *http.Request) {
s.respondJSON(w, r, &response{Now: time.Now()}, 200)
}
}

View File

@@ -7,9 +7,9 @@ import (
basicauth "github.com/99designs/basicauth-go"
"github.com/go-chi/chi/middleware"
"github.com/go-chi/cors"
metrics "github.com/slok/go-http-metrics/metrics/prometheus"
ghmm "github.com/slok/go-http-metrics/middleware"
"github.com/slok/go-http-metrics/middleware/std"
"github.com/spf13/viper"
)
@@ -75,10 +75,25 @@ func (s *server) LoggingMiddleware() func(http.Handler) http.Handler {
}
}
func (s *server) CORSMiddleware() func(http.Handler) http.Handler {
return cors.Handler(cors.Options{
// CHANGEME! these are defaults, change them to suit your needs or
// read from environment/viper.
// AllowedOrigins: []string{"https://foo.com"}, // Use this to allow specific origin hosts
AllowedOrigins: []string{"*"},
// AllowOriginFunc: func(r *http.Request, origin string) bool { return true },
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: false,
MaxAge: 300, // Maximum value not ignored by any of major browsers
})
}
func (s *server) AuthMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// FIXME you'll want to change this to do stuff.
// CHANGEME you'll want to change this to do stuff.
s.log.Info().Msg("AUTH: before request")
next.ServeHTTP(w, r)
})

View File

@@ -30,6 +30,10 @@ func (s *server) routes() {
s.router.Use(s.MetricsMiddleware())
}
// set up CORS headers. you'll probably want to configure that
// in middlewares.go.
s.router.Use(s.CORSMiddleware())
// CHANGEME to suit your needs, or pull from config.
// timeout for request context; your handlers must finish within
// this window:
@@ -55,6 +59,12 @@ func (s *server) routes() {
s.router.Get("/", s.handleIndex())
s.router.Get("/", s.handleIndex())
s.router.Route("/api/v1", func(r chi.Router) {
r.Get("/now", s.handleNow())
})
// if you want to use a general purpose middleware (http.Handler
// wrapper) on a specific HandleFunc route, you need to take the
// .ServeHTTP of the http.Handler to get its HandleFunc, viz: