Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support validator interface in JSONHandler #14

Merged
merged 2 commits into from
Feb 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
version: 2
updates:
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "weekly"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
5 changes: 3 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ on:

concurrency:
group: ${{ github.workflow }}-${{ github.ref_name }}
cancel-in-progress: true
cancel-in-progress: ${{ github.ref_name != 'main' }}

jobs:
test:
Expand All @@ -36,6 +36,7 @@ jobs:
lint:
name: Lint
runs-on: ubuntu-latest
if: ${{ github.triggering_actor != 'dependabot[bot]' }}

steps:
- name: Checkout
Expand All @@ -48,6 +49,6 @@ jobs:
check-latest: true

- name: Lint
uses: golangci/golangci-lint-action@v4
uses: golangci/golangci-lint-action@v6
with:
version: latest
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# httph

[![GoDoc](https://pkg.go.dev/badge/maragu.dev/httph)](https://pkg.go.dev/maragu.dev/httph)
[![Go](https://github.com/maragudk/httph/actions/workflows/ci.yml/badge.svg)](https://github.com/maragudk/httph/actions/workflows/ci.yml)
[![CI](https://github.com/maragudk/httph/actions/workflows/ci.yml/badge.svg)](https://github.com/maragudk/httph/actions/workflows/ci.yml)

HTTP helpers and middleware. H is for helpful!

```shell
go get maragu.dev/httph
```

Made in 🇩🇰 by [maragu](https://www.maragu.dk/), maker of [online Go courses](https://www.golang.dk/).
Made with ✨sparkles✨ by [maragu](https://www.maragu.dev/).
7 changes: 3 additions & 4 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ module maragu.dev/httph

go 1.19

require (
github.com/maragudk/is v0.1.0
github.com/mitchellh/mapstructure v1.5.0
)
require github.com/mitchellh/mapstructure v1.5.0

require maragu.dev/is v0.2.0
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
github.com/maragudk/is v0.1.0 h1:obq9anZNmOYcaNbeT0LMyjIexdNeYTw/TLAPD/BnZHA=
github.com/maragudk/is v0.1.0/go.mod h1:W/r6+TpnISu+a88OLXQy5JQGCOhXQXXLD2e5b4xMn5c=
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
maragu.dev/is v0.2.0 h1:poeuVEA5GG3vrDpGmzo2KjWtIMZmqUyvGnOB0/pemig=
maragu.dev/is v0.2.0/go.mod h1:bviaM5S0fBshCw7wuumFGTju/izopZ/Yvq4g7Klc7y8=
12 changes: 12 additions & 0 deletions httph.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,11 @@ func JSONHandler[Req any, Res any](h func(http.ResponseWriter, *http.Request, Re
}

// Try reading a request body, skip if there is none
var foundRequestBody bool
br := bufio.NewReader(r.Body)
if _, err := br.Peek(1); err == nil {
dec := json.NewDecoder(br)
foundRequestBody = true

if err := dec.Decode(&req); err != nil {
w.WriteHeader(http.StatusBadRequest)
Expand All @@ -91,6 +93,16 @@ func JSONHandler[Req any, Res any](h func(http.ResponseWriter, *http.Request, Re
}
}

if req, ok := any(req).(validator); ok && foundRequestBody {
if err := req.Validate(); err != nil {
w.WriteHeader(http.StatusBadRequest)
writeResponse(w, errorResponse{
Error: fmt.Errorf("invalid request body: %w", err).Error(),
})
return
}
}

res, err := h(w, r, req)
if err != nil {
code := http.StatusInternalServerError
Expand Down
29 changes: 27 additions & 2 deletions httph_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ import (
"strings"
"testing"

"github.com/maragudk/is"

"maragu.dev/httph"
"maragu.dev/is"
)

type validatedFormReq struct{}
Expand Down Expand Up @@ -156,6 +155,17 @@ func (t tinyJSONReq) MaxSizeBytes() int64 {
return 1
}

type validatedJSONReq struct {
Name string
}

func (v validatedJSONReq) Validate() error {
if v.Name == "" {
return errors.New("name cannot be empty")
}
return nil
}

func TestJSONHandler(t *testing.T) {
t.Run("encodes response body to JSON", func(t *testing.T) {
type jsonRes struct {
Expand Down Expand Up @@ -283,6 +293,21 @@ func TestJSONHandler(t *testing.T) {
is.Equal(t, http.StatusBadRequest, res.Result().StatusCode)
is.Equal(t, `{"Error":"error decoding request body as JSON: http: request body too large"}`, readBody(t, res))
})

t.Run("returns bad request if request body fails validation", func(t *testing.T) {
h := httph.JSONHandler(func(w http.ResponseWriter, r *http.Request, req validatedJSONReq) (any, error) {
return nil, nil
})

req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(`{"Name":""}`))
req.Header.Set("Content-Type", "application/json")
res := httptest.NewRecorder()

h.ServeHTTP(res, req)

is.Equal(t, http.StatusBadRequest, res.Result().StatusCode)
is.Equal(t, `{"Error":"invalid request body: name cannot be empty"}`, readBody(t, res))
})
}

func ExampleJSONHandler() {
Expand Down