Add FormTrimmed #61

Merged
lunny merged 1 commits from lunny/add_form_space into master 2019-08-21 06:31:28 +00:00
2 changed files with 44 additions and 0 deletions

16
form.go

@ -10,6 +10,7 @@ import (
"net/http"
"net/url"
"strconv"
"strings"
)
// Forms a new enhancement of http.Request
@ -27,6 +28,11 @@ func (f *Forms) String(key string) (string, error) {
return (*http.Request)(f).FormValue(key), nil
}
// TrimSpace returns request form as string with trimed spaces left and right
func (f *Forms) Trimmed(key string) (string, error) {
return strings.TrimSpace((*http.Request)(f).FormValue(key)), nil
}
// Strings returns request form as strings
func (f *Forms) Strings(key string) ([]string, error) {
(*http.Request)(f).ParseMultipartForm(32 << 20)
@ -101,6 +107,11 @@ func (f *Forms) MustString(key string, defaults ...string) string {
return ""
}
// MustTrimmed returns request form as string with default
func (f *Forms) MustTrimmed(key string, defaults ...string) string {
return strings.TrimSpace(f.MustString(key, defaults...))
}
// MustStrings returns request form as strings with default
func (f *Forms) MustStrings(key string, defaults ...[]string) []string {
(*http.Request)(f).ParseMultipartForm(32 << 20)
@ -210,6 +221,11 @@ func (ctx *Context) Form(key string, defaults ...string) string {
return (*Forms)(ctx.req).MustString(key, defaults...)
}
// FormTrimmed returns request form as string with default and trimmed spaces
func (ctx *Context) FormTrimmed(key string, defaults ...string) string {
return (*Forms)(ctx.req).MustTrimmed(key, defaults...)
}
// FormStrings returns request form as strings with default
func (ctx *Context) FormStrings(key string, defaults ...[]string) []string {
return (*Forms)(ctx.req).MustStrings(key, defaults...)

@ -853,3 +853,31 @@ func TestForm30(t *testing.T) {
refute(t, len(buff.String()), 0)
expect(t, buff.String(), "1")
}
type Form31Action struct {
Ctx
}
func (a *Form31Action) Get() string {
v := a.FormTrimmed("test")
return fmt.Sprintf("%s", v)
}
func TestForm31(t *testing.T) {
buff := bytes.NewBufferString("")
recorder := httptest.NewRecorder()
recorder.Body = buff
o := Classic()
o.Get("/", new(Form31Action))
req, err := http.NewRequest("GET", "http://localhost:8000/?test=1%20", nil)
if err != nil {
t.Error(err)
}
o.ServeHTTP(recorder, req)
expect(t, recorder.Code, http.StatusOK)
refute(t, len(buff.String()), 0)
expect(t, buff.String(), "1")
}