Skip to content

Commit

Permalink
Merge pull request #74 from calvinmclean/feature/responsewriter
Browse files Browse the repository at this point in the history
Add ResponseWriter to remaining handlers
  • Loading branch information
calvinmclean authored Aug 10, 2024
2 parents f0d1341 + 7e7756d commit 207e8b6
Show file tree
Hide file tree
Showing 6 changed files with 22 additions and 22 deletions.
8 changes: 4 additions & 4 deletions babyapi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ func TestBabyAPI(t *testing.T) {
w.WriteHeader(http.StatusTeapot)
}))

api.AddCustomIDRoute(http.MethodGet, "/teapot", api.GetRequestedResourceAndDo(func(r *http.Request, album *Album) (render.Renderer, *babyapi.ErrResponse) {
api.AddCustomIDRoute(http.MethodGet, "/teapot", api.GetRequestedResourceAndDo(func(_ http.ResponseWriter, r *http.Request, album *Album) (render.Renderer, *babyapi.ErrResponse) {
render.Status(r, http.StatusTeapot)
return album, nil
}))
Expand Down Expand Up @@ -634,7 +634,7 @@ func (ul *UnorderedList) Render(w http.ResponseWriter, r *http.Request) error {
return nil
}

func (ul *UnorderedList) HTML(r *http.Request) string {
func (ul *UnorderedList) HTML(_ http.ResponseWriter, r *http.Request) string {
templates := map[string]string{
"ul": `<ul>
{{- range .Items }}
Expand All @@ -652,7 +652,7 @@ type ListItem struct {
Content string
}

func (d *ListItem) HTML(*http.Request) string {
func (d *ListItem) HTML(http.ResponseWriter, *http.Request) string {
tmpl := template.Must(template.New("li").Parse(`<li>{{ .Content }}</li>`))
return babyapi.MustRenderHTML(tmpl, d)
}
Expand Down Expand Up @@ -810,7 +810,7 @@ func TestAPIModifiers(t *testing.T) {
})

api.AddIDMiddleware(api.GetRequestedResourceAndDoMiddleware(
func(r *http.Request, a *Album) (*http.Request, *babyapi.ErrResponse) {
func(_ http.ResponseWriter, r *http.Request, a *Album) (*http.Request, *babyapi.ErrResponse) {
require.NotNil(t, a)
idMiddlewareWithRequestResource++
return r, nil
Expand Down
12 changes: 6 additions & 6 deletions examples/event-rsvp/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func (api *API) export(w http.ResponseWriter, r *http.Request) render.Renderer {
}

// Use a custom route to set RSVP so rsvpResponse can be used to return HTML buttons
func (api *API) rsvp(r *http.Request, invite *Invite) (render.Renderer, *babyapi.ErrResponse) {
func (api *API) rsvp(_ http.ResponseWriter, r *http.Request, invite *Invite) (render.Renderer, *babyapi.ErrResponse) {
if err := r.ParseForm(); err != nil {
return nil, babyapi.ErrInvalidRequest(fmt.Errorf("error parsing form data: %w", err))
}
Expand All @@ -116,7 +116,7 @@ func (api *API) rsvp(r *http.Request, invite *Invite) (render.Renderer, *babyapi
}

// Allow adding bulk invites with a single request
func (api *API) addBulkInvites(r *http.Request, event *Event) (render.Renderer, *babyapi.ErrResponse) {
func (api *API) addBulkInvites(_ http.ResponseWriter, r *http.Request, event *Event) (render.Renderer, *babyapi.ErrResponse) {
if err := r.ParseForm(); err != nil {
return nil, babyapi.ErrInvalidRequest(fmt.Errorf("error parsing form data: %w", err))
}
Expand Down Expand Up @@ -154,7 +154,7 @@ func (api *API) addBulkInvites(r *http.Request, event *Event) (render.Renderer,
// authenticationMiddleware enforces access to Events and Invites. Admin access to an Event requires a password query parameter.
// Access to Invites is allowed by the invite ID and requires no extra auth. The invite ID in the path or query parameter allows
// read-only access to the Event
func (api *API) authenticationMiddleware(r *http.Request, event *Event) (*http.Request, *babyapi.ErrResponse) {
func (api *API) authenticationMiddleware(_ http.ResponseWriter, r *http.Request, event *Event) (*http.Request, *babyapi.ErrResponse) {
password := r.URL.Query().Get("password")
inviteID := r.URL.Query().Get("invite")
if inviteID == "" {
Expand Down Expand Up @@ -184,7 +184,7 @@ func (api *API) authenticationMiddleware(r *http.Request, event *Event) (*http.R
}

// getAllInvitesMiddleware will get all invites when rendering HTML so it is accessible to the endpoint
func (api *API) getAllInvitesMiddleware(r *http.Request, event *Event) (*http.Request, *babyapi.ErrResponse) {
func (api *API) getAllInvitesMiddleware(_ http.ResponseWriter, r *http.Request, event *Event) (*http.Request, *babyapi.ErrResponse) {
if render.GetAcceptedContentType(r) != render.ContentTypeHTML {
return r, nil
}
Expand Down Expand Up @@ -265,7 +265,7 @@ func (e *Event) Bind(r *http.Request) error {
return e.DefaultResource.Bind(r)
}

func (e *Event) HTML(r *http.Request) string {
func (e *Event) HTML(_ http.ResponseWriter, r *http.Request) string {
return eventPage.Render(r, struct {
Password string
*Event
Expand Down Expand Up @@ -300,7 +300,7 @@ func (i *Invite) Bind(r *http.Request) error {
return i.DefaultResource.Bind(r)
}

func (i *Invite) HTML(r *http.Request) string {
func (i *Invite) HTML(_ http.ResponseWriter, r *http.Request) string {
event, _ := babyapi.GetResourceFromContext[*Event](r.Context(), babyapi.ContextKey("Event"))

return invitePage.Render(r, struct {
Expand Down
10 changes: 5 additions & 5 deletions examples/todo-htmx/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ type TODO struct {
Completed *bool
}

func (t *TODO) HTML(r *http.Request) string {
func (t *TODO) HTML(_ http.ResponseWriter, r *http.Request) string {
return todoRow.Render(r, t)
}

Expand All @@ -120,7 +120,7 @@ func (at AllTODOs) Render(w http.ResponseWriter, r *http.Request) error {
return nil
}

func (at AllTODOs) HTML(r *http.Request) string {
func (at AllTODOs) HTML(_ http.ResponseWriter, r *http.Request) string {
return allTODOs.Render(r, at.Items)
}

Expand All @@ -131,7 +131,7 @@ func createAPI() *babyapi.API[*TODO] {

// Use AllTODOs in the GetAll response since it implements HTMLer
api.SetGetAllResponseWrapper(func(todos []*TODO) render.Renderer {
return AllTODOs{ResourceList: babyapi.ResourceList[*TODO]{todos}}
return AllTODOs{ResourceList: babyapi.ResourceList[*TODO]{Items: todos}}
})

api.ApplyExtension(extensions.HTMX[*TODO]{})
Expand All @@ -140,13 +140,13 @@ func createAPI() *babyapi.API[*TODO] {
todoChan := api.AddServerSentEventHandler("/listen")

// Push events onto the SSE channel when new TODOs are created
api.SetOnCreateOrUpdate(func(_ http.ResponseWriter, r *http.Request, t *TODO) *babyapi.ErrResponse {
api.SetOnCreateOrUpdate(func(w http.ResponseWriter, r *http.Request, t *TODO) *babyapi.ErrResponse {
if r.Method != http.MethodPost {
return nil
}

select {
case todoChan <- &babyapi.ServerSentEvent{Event: "newTODO", Data: t.HTML(r)}:
case todoChan <- &babyapi.ServerSentEvent{Event: "newTODO", Data: t.HTML(w, r)}:
default:
logger := babyapi.GetLoggerFromContext(r.Context())
logger.Info("no listeners for server-sent event")
Expand Down
8 changes: 4 additions & 4 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ func (a *API[T]) findIDParam(r *http.Request) string {

// GetRequestedResourceAndDo is a wrapper that handles getting a resource from storage based on the ID in the request URL
// and rendering the response. This is useful for imlementing a CustomIDRoute
func (a *API[T]) GetRequestedResourceAndDo(do func(*http.Request, T) (render.Renderer, *ErrResponse)) http.HandlerFunc {
func (a *API[T]) GetRequestedResourceAndDo(do func(http.ResponseWriter, *http.Request, T) (render.Renderer, *ErrResponse)) http.HandlerFunc {
return Handler(func(w http.ResponseWriter, r *http.Request) render.Renderer {
logger := GetLoggerFromContext(r.Context())

Expand All @@ -82,7 +82,7 @@ func (a *API[T]) GetRequestedResourceAndDo(do func(*http.Request, T) (render.Ren
return httpErr
}

resp, httpErr := do(r, resource)
resp, httpErr := do(w, r, resource)
if httpErr != nil {
return httpErr
}
Expand All @@ -99,7 +99,7 @@ func (a *API[T]) GetRequestedResourceAndDo(do func(*http.Request, T) (render.Ren
// GetRequestedResourceAndDoMiddleware is a shortcut for creating an ID-scoped middleware that gets the requested resource from storage,
// calls the provided 'do' function, and calls next.ServeHTTP. If the resource is not found for a PUT request, the error is ignored
// The 'do' function returns *http.Request so the request context can be modified by middleware
func (a *API[T]) GetRequestedResourceAndDoMiddleware(do func(*http.Request, T) (*http.Request, *ErrResponse)) func(next http.Handler) http.Handler {
func (a *API[T]) GetRequestedResourceAndDoMiddleware(do func(http.ResponseWriter, *http.Request, T) (*http.Request, *ErrResponse)) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {

Expand All @@ -119,7 +119,7 @@ func (a *API[T]) GetRequestedResourceAndDoMiddleware(do func(*http.Request, T) (
return
}

r, httpErr = do(r, resource)
r, httpErr = do(w, r, resource)
if httpErr != nil {
_ = render.Render(w, r, httpErr)
return
Expand Down
2 changes: 1 addition & 1 deletion html/templates.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,6 @@ func (h htmlRenderer) Render(_ http.ResponseWriter, _ *http.Request) error {
return nil
}

func (h htmlRenderer) HTML(r *http.Request) string {
func (h htmlRenderer) HTML(_ http.ResponseWriter, r *http.Request) string {
return h.t.Render(r, h.data)
}
4 changes: 2 additions & 2 deletions router.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ var _ error = BuilderError{}
// HTMLer allows for easily represending reponses as HTML strings when accepted content
// type is text/html
type HTMLer interface {
HTML(*http.Request) string
HTML(http.ResponseWriter, *http.Request) string
}

// EnableHTMLRender overrides the default render.Respond function to add support for the
Expand All @@ -56,7 +56,7 @@ func EnableHTMLRender() {
if render.GetAcceptedContentType(r) == render.ContentTypeHTML {
htmler, ok := v.(HTMLer)
if ok {
render.HTML(w, r, htmler.HTML(r))
render.HTML(w, r, htmler.HTML(w, r))
return
}
}
Expand Down

0 comments on commit 207e8b6

Please sign in to comment.