|
| 1 | +package nchi_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/xml" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "net/http" |
| 9 | + "net/http/httptest" |
| 10 | + "strings" |
| 11 | + "testing" |
| 12 | + |
| 13 | + "github.com/muir/nchi" |
| 14 | + "github.com/muir/nvelope" |
| 15 | + |
| 16 | + "github.com/stretchr/testify/assert" |
| 17 | +) |
| 18 | + |
| 19 | +type bodyData struct { |
| 20 | + I int `json:"i"` |
| 21 | +} |
| 22 | + |
| 23 | +type parameters struct { |
| 24 | + Body bodyData `nvelope:"model"` |
| 25 | + Zoom int `nvelope:"path,name=zoomie"` |
| 26 | + Who string `nvelope:"query,name=who"` |
| 27 | +} |
| 28 | + |
| 29 | +func TestDecoders(t *testing.T) { |
| 30 | + mux := nchi.NewRouter(nchi.WithRedirectFixedPath(true)) |
| 31 | + mux.Use(nvelope.MinimalErrorHandler, nvelope.ReadBody) |
| 32 | + mux.Post("/td1/:zoomie/foo", nchi.DecodeJSON, func(p parameters, w http.ResponseWriter) { |
| 33 | + _, _ = w.Write([]byte(fmt.Sprintf("bi %d z %d w %s", p.Body.I, p.Zoom, p.Who))) |
| 34 | + }) |
| 35 | + mux.Post("/td2/:zoomie/bar", nchi.DecodeXML, func(p parameters, w http.ResponseWriter) { |
| 36 | + _, _ = w.Write([]byte(fmt.Sprintf("bi %d z %d w %s", p.Body.I, p.Zoom, p.Who))) |
| 37 | + }) |
| 38 | + |
| 39 | + w := httptest.NewRecorder() |
| 40 | + r := httptest.NewRequest("POST", "/td1/9/foo?who=john", strings.NewReader(`{"I":3}`)) |
| 41 | + mux.ServeHTTP(w, r) |
| 42 | + body, err := io.ReadAll(w.Result().Body) |
| 43 | + assert.NoError(t, err, "/td1") |
| 44 | + got := string(body) |
| 45 | + t.Log("/td1/9/foo?who=john ->", got) |
| 46 | + assert.Equal(t, "bi 3 z 9 w john", got, "/td1") |
| 47 | + |
| 48 | + enc, err := xml.Marshal(bodyData{I: 19}) |
| 49 | + assert.NoError(t, err, "marshal xml") |
| 50 | + w = httptest.NewRecorder() |
| 51 | + r = httptest.NewRequest("POST", "/td2/11/bar?who=mary", bytes.NewReader(enc)) |
| 52 | + mux.ServeHTTP(w, r) |
| 53 | + body, err = io.ReadAll(w.Result().Body) |
| 54 | + assert.NoError(t, err, "/td2") |
| 55 | + got = string(body) |
| 56 | + t.Log("/td2/11/bar?who=mary ->", got) |
| 57 | + assert.Equal(t, "bi 19 z 11 w mary", got, "/td2") |
| 58 | +} |
0 commit comments