Преглед на файлове

add form package (gorilla/schema based)

tags/v0.9.0
jimzhan преди 9 години
родител
ревизия
f64abf691e
променени са 3 файла, в които са добавени 86 реда и са изтрити 24 реда
  1. +24
    -0
      form/form.go
  2. +62
    -0
      form/form_test.go
  3. +0
    -24
      schema.go

+ 24
- 0
form/form.go Целия файл

@@ -0,0 +1,24 @@
package form

import (
"net/http"

. "github.com/gorilla/schema"
)

var schema = NewDecoder()

type Validator interface {
Validate() error
}

// Parse parsed the raw query from the URL and updates request.Form,
// decode the from to the given struct with Validator implemented.
func Parse(r *http.Request, form Validator) (err error) {
if err = r.ParseForm(); err == nil {
if err = schema.Decode(form, r.Form); err == nil {
err = form.Validate()
}
}
return
}

+ 62
- 0
form/form_test.go Целия файл

@@ -0,0 +1,62 @@
package form

import (
"bytes"
"errors"
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"

. "github.com/smartystreets/goconvey/convey"
)

type user struct {
Username string `schema:"username"`
Password string `schema:"password"`
}

func (self *user) Validate() error {
if self.Username == "" || self.Password == "" {
return errors.New("username/password can not be empty")
}

if len(self.Password) < 8 {
return errors.New("password must be greater than 8bits")
}
return nil
}

func TestParse(t *testing.T) {
app := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var form user
if err := Parse(r, &form); err == nil {
w.WriteHeader(http.StatusAccepted)
io.WriteString(w, "uid")
} else {
w.WriteHeader(http.StatusBadRequest)
io.WriteString(w, err.Error())
}
})

Convey("rex.form.Parse", t, func() {
values := url.Values{}
values.Set("username", "username")
values.Set("password", "password")

request, _ := http.NewRequest("POST", "/", bytes.NewBufferString(values.Encode()))
request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
response := httptest.NewRecorder()

app.ServeHTTP(response, request)
So(response.Code, ShouldEqual, http.StatusAccepted)

values.Set("password", "7")
request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(values.Encode()))
response = httptest.NewRecorder()

app.ServeHTTP(response, request)
So(response.Code, ShouldEqual, http.StatusBadRequest)
})
}

+ 0
- 24
schema.go Целия файл

@@ -1,24 +0,0 @@
package rex

import (
"net/http"

"github.com/gorilla/schema"
)

var Schema = schema.NewDecoder()

type Validator interface {
Validate() error
}

// ParseForm parsed the raw query from the URL and updates request.Form,
// decode the from to the given struct with Validator implemented.
func ParseForm(r *http.Request, form Validator) (err error) {
if err = r.ParseForm(); err == nil {
if err = Schema.Decode(form, r.Form); err == nil {
err = form.Validate()
}
}
return
}

Loading…
Отказ
Запис