From 22a40c7402193e8fc7f72088324986ef05df1c46 Mon Sep 17 00:00:00 2001 From: Brad Sickles Date: Fri, 2 Jun 2023 09:58:25 -0400 Subject: [PATCH] Added json.Controller --- go.mod | 10 ++++++++-- json/controller.go | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 json/controller.go diff --git a/go.mod b/go.mod index 2dc45f7..a075bd5 100644 --- a/go.mod +++ b/go.mod @@ -1,14 +1,20 @@ module github.com/BSick7/go-api -go 1.13 +go 1.18 require ( github.com/cristalhq/jwt/v3 v3.0.4 github.com/google/uuid v1.3.0 github.com/gorilla/handlers v1.4.2 github.com/gorilla/mux v1.7.4 - github.com/klauspost/compress v1.13.4 // indirect github.com/stretchr/testify v1.7.0 github.com/svanharmelen/jsonapi v0.0.0-20180618144545-0c0828c3f16d github.com/xi2/httpgzip v0.0.0-20190509075255-932ab5e254ae ) + +require ( + github.com/davecgh/go-spew v1.1.0 // indirect + github.com/klauspost/compress v1.13.4 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect +) diff --git a/json/controller.go b/json/controller.go new file mode 100644 index 0000000..ada4aca --- /dev/null +++ b/json/controller.go @@ -0,0 +1,21 @@ +package json + +import ( + "net/http" + "time" +) + +type ControllerFunc[T any] func(req *Request) (T, error) + +func Controller[T any](controller ControllerFunc[T]) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + res := &ResponseWriter{ResponseWriter: w, start: time.Now()} + req := &Request{Request: r} + if out, err := controller(req); err != nil { + res.SendError(err) + } else { + res.Send(out) + } + }) +}