1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-25 10:00:56 +00:00

add comments for testing, utils and validation packages

This commit is contained in:
傅小黑 2014-02-07 16:07:31 +08:00
parent 846d766499
commit ce2984f09a
9 changed files with 64 additions and 7 deletions

View File

@ -8,6 +8,7 @@ import (
var port = ""
var baseUrl = "http://localhost:"
// beego test request client
type TestHttpRequest struct {
httplib.BeegoHttpRequest
}
@ -24,22 +25,27 @@ func getPort() string {
return port
}
// returns test client in GET method
func Get(path string) *TestHttpRequest {
return &TestHttpRequest{*httplib.Get(baseUrl + getPort() + path)}
}
// returns test client in POST method
func Post(path string) *TestHttpRequest {
return &TestHttpRequest{*httplib.Post(baseUrl + getPort() + path)}
}
// returns test client in PUT method
func Put(path string) *TestHttpRequest {
return &TestHttpRequest{*httplib.Put(baseUrl + getPort() + path)}
}
// returns test client in DELETE method
func Delete(path string) *TestHttpRequest {
return &TestHttpRequest{*httplib.Delete(baseUrl + getPort() + path)}
}
// returns test client in HEAD method
func Head(path string) *TestHttpRequest {
return &TestHttpRequest{*httplib.Head(baseUrl + getPort() + path)}
}

View File

@ -5,6 +5,7 @@ import (
"runtime"
)
// get function name
func GetFuncName(i interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}

View File

@ -70,6 +70,7 @@ const (
urlPrefix = "/captcha/"
)
// Captcha struct
type Captcha struct {
// beego cache store
store cache.Cache
@ -96,10 +97,12 @@ type Captcha struct {
CachePrefix string
}
// generate key string
func (c *Captcha) key(id string) string {
return c.CachePrefix + id
}
// generate rand chars with default chars
func (c *Captcha) genRandChars() []byte {
return utils.RandomCreateBytes(c.ChallengeNums, defaultChars...)
}

View File

@ -9,11 +9,13 @@ import (
"regexp"
)
// SelfPath gets compiled executable file absolute path
func SelfPath() string {
path, _ := filepath.Abs(os.Args[0])
return path
}
// SelfDir gets compiled executable file directory
func SelfDir() string {
return filepath.Dir(SelfPath())
}
@ -28,8 +30,8 @@ func FileExists(name string) bool {
return true
}
// search a file in paths.
// this is offen used in search config file in /etc ~/
// Search a file in paths.
// this is often used in search config file in /etc ~/
func SearchFile(filename string, paths ...string) (fullpath string, err error) {
for _, path := range paths {
if fullpath = filepath.Join(path, filename); FileExists(fullpath) {

View File

@ -51,6 +51,8 @@ type Attachment struct {
Content []byte
}
// NewEMail create new Email struct with config json.
// config json is followed from Email struct fields.
func NewEMail(config string) *Email {
e := new(Email)
e.Headers = textproto.MIMEHeader{}
@ -64,7 +66,7 @@ func NewEMail(config string) *Email {
return e
}
// make all send information to byte
// Make all send information to byte
func (e *Email) Bytes() ([]byte, error) {
buff := &bytes.Buffer{}
w := multipart.NewWriter(buff)
@ -140,7 +142,7 @@ func (e *Email) Bytes() ([]byte, error) {
return buff.Bytes(), nil
}
// Attach file to the send mail
// Add attach file to the send mail
func (e *Email) AttachFile(filename string) (a *Attachment, err error) {
f, err := os.Open(filename)
if err != nil {
@ -152,7 +154,7 @@ func (e *Email) AttachFile(filename string) (a *Attachment, err error) {
}
// Attach is used to attach content from an io.Reader to the email.
// Required parameters include an io.Reader, the desired filename for the attachment, and the Content-Type
// Parameters include an io.Reader, the desired filename for the attachment, and the Content-Type.
func (e *Email) Attach(r io.Reader, filename string, c string) (a *Attachment, err error) {
var buffer bytes.Buffer
if _, err = io.Copy(&buffer, r); err != nil {
@ -275,7 +277,7 @@ func headerToBytes(w io.Writer, t textproto.MIMEHeader) error {
return nil
}
// base64Wrap encodeds the attachment content, and wraps it according to RFC 2045 standards (every 76 chars)
// base64Wrap encodes the attachment content, and wraps it according to RFC 2045 standards (every 76 chars)
// The output is then written to the specified io.Writer
func base64Wrap(w io.Writer, b []byte) {
// 57 raw bytes per 76-byte base64 line.

View File

@ -9,6 +9,7 @@ type BeeMap struct {
bm map[interface{}]interface{}
}
// NewBeeMap return new safemap
func NewBeeMap() *BeeMap {
return &BeeMap{
lock: new(sync.RWMutex),
@ -16,7 +17,7 @@ func NewBeeMap() *BeeMap {
}
}
//Get from maps return the k's value
// Get from maps return the k's value
func (m *BeeMap) Get(k interface{}) interface{} {
m.lock.RLock()
defer m.lock.RUnlock()
@ -51,12 +52,14 @@ func (m *BeeMap) Check(k interface{}) bool {
return true
}
// Delete the given key and value.
func (m *BeeMap) Delete(k interface{}) {
m.lock.Lock()
defer m.lock.Unlock()
delete(m.bm, k)
}
// Items returns all items in safemap.
func (m *BeeMap) Items() map[interface{}]interface{} {
m.lock.RLock()
defer m.lock.RUnlock()

View File

@ -8,6 +8,7 @@ import (
type reducetype func(interface{}) interface{}
type filtertype func(interface{}) bool
// InSlice checks given string in string slice or not.
func InSlice(v string, sl []string) bool {
for _, vv := range sl {
if vv == v {
@ -17,6 +18,7 @@ func InSlice(v string, sl []string) bool {
return false
}
// InSliceIface checks given interface in interface slice.
func InSliceIface(v interface{}, sl []interface{}) bool {
for _, vv := range sl {
if vv == v {
@ -26,6 +28,7 @@ func InSliceIface(v interface{}, sl []interface{}) bool {
return false
}
// SliceRandList generate an int slice from min to max.
func SliceRandList(min, max int) []int {
if max < min {
min, max = max, min
@ -40,11 +43,13 @@ func SliceRandList(min, max int) []int {
return list
}
// SliceMerge merges interface slices to one slice.
func SliceMerge(slice1, slice2 []interface{}) (c []interface{}) {
c = append(slice1, slice2...)
return
}
// SliceReduce generates a new slice after parsing every value by reduce function
func SliceReduce(slice []interface{}, a reducetype) (dslice []interface{}) {
for _, v := range slice {
dslice = append(dslice, a(v))
@ -52,12 +57,14 @@ func SliceReduce(slice []interface{}, a reducetype) (dslice []interface{}) {
return
}
// SliceRand returns random one from slice.
func SliceRand(a []interface{}) (b interface{}) {
randnum := rand.Intn(len(a))
b = a[randnum]
return
}
// SliceSum sums all values in int64 slice.
func SliceSum(intslice []int64) (sum int64) {
for _, v := range intslice {
sum += v
@ -65,6 +72,7 @@ func SliceSum(intslice []int64) (sum int64) {
return
}
// SliceFilter generates a new slice after filter function.
func SliceFilter(slice []interface{}, a filtertype) (ftslice []interface{}) {
for _, v := range slice {
if a(v) {
@ -74,6 +82,7 @@ func SliceFilter(slice []interface{}, a filtertype) (ftslice []interface{}) {
return
}
// SliceDiff returns diff slice of slice1 - slice2.
func SliceDiff(slice1, slice2 []interface{}) (diffslice []interface{}) {
for _, v := range slice1 {
if !InSliceIface(v, slice2) {
@ -83,6 +92,7 @@ func SliceDiff(slice1, slice2 []interface{}) (diffslice []interface{}) {
return
}
// SliceIntersect returns diff slice of slice2 - slice1.
func SliceIntersect(slice1, slice2 []interface{}) (diffslice []interface{}) {
for _, v := range slice1 {
if !InSliceIface(v, slice2) {
@ -92,6 +102,7 @@ func SliceIntersect(slice1, slice2 []interface{}) (diffslice []interface{}) {
return
}
// SliceChuck separates one slice to some sized slice.
func SliceChunk(slice []interface{}, size int) (chunkslice [][]interface{}) {
if size >= len(slice) {
chunkslice = append(chunkslice, slice)
@ -105,6 +116,7 @@ func SliceChunk(slice []interface{}, size int) (chunkslice [][]interface{}) {
return
}
// SliceRange generates a new slice from begin to end with step duration of int64 number.
func SliceRange(start, end, step int64) (intslice []int64) {
for i := start; i <= end; i += step {
intslice = append(intslice, i)
@ -112,6 +124,7 @@ func SliceRange(start, end, step int64) (intslice []int64) {
return
}
// SlicePad prepends size number of val into slice.
func SlicePad(slice []interface{}, size int, val interface{}) []interface{} {
if size <= len(slice) {
return slice
@ -122,6 +135,7 @@ func SlicePad(slice []interface{}, size int, val interface{}) []interface{} {
return slice
}
// SliceUnique cleans repeated values in slice.
func SliceUnique(slice []interface{}) (uniqueslice []interface{}) {
for _, v := range slice {
if !InSliceIface(v, uniqueslice) {
@ -131,6 +145,7 @@ func SliceUnique(slice []interface{}) (uniqueslice []interface{}) {
return
}
// SliceShuffle shuffles a slice.
func SliceShuffle(slice []interface{}) []interface{} {
for i := 0; i < len(slice); i++ {
a := rand.Intn(len(slice))

View File

@ -41,13 +41,16 @@ func init() {
}
}
// Valid function type
type ValidFunc struct {
Name string
Params []interface{}
}
// Validate function map
type Funcs map[string]reflect.Value
// validate values with named type string
func (f Funcs) Call(name string, params ...interface{}) (result []reflect.Value, err error) {
defer func() {
if r := recover(); r != nil {

View File

@ -32,6 +32,7 @@ type ValidationResult struct {
Ok bool
}
// Get ValidationResult by given key string.
func (r *ValidationResult) Key(key string) *ValidationResult {
if r.Error != nil {
r.Error.Key = key
@ -39,6 +40,7 @@ func (r *ValidationResult) Key(key string) *ValidationResult {
return r
}
// Set ValidationResult message by string or format string with args
func (r *ValidationResult) Message(message string, args ...interface{}) *ValidationResult {
if r.Error != nil {
if len(args) == 0 {
@ -56,10 +58,12 @@ type Validation struct {
ErrorsMap map[string]*ValidationError
}
// Clean all ValidationError.
func (v *Validation) Clear() {
v.Errors = []*ValidationError{}
}
// Has ValidationError nor not.
func (v *Validation) HasErrors() bool {
return len(v.Errors) > 0
}
@ -101,67 +105,83 @@ func (v *Validation) Range(obj interface{}, min, max int, key string) *Validatio
return v.apply(Range{Min{Min: min}, Max{Max: max}, key}, obj)
}
// Test that the obj is longer than min size if type is string or slice
func (v *Validation) MinSize(obj interface{}, min int, key string) *ValidationResult {
return v.apply(MinSize{min, key}, obj)
}
// Test that the obj is shorter than max size if type is string or slice
func (v *Validation) MaxSize(obj interface{}, max int, key string) *ValidationResult {
return v.apply(MaxSize{max, key}, obj)
}
// Test that the obj is same length to n if type is string or slice
func (v *Validation) Length(obj interface{}, n int, key string) *ValidationResult {
return v.apply(Length{n, key}, obj)
}
// Test that the obj is [a-zA-Z] if type is string
func (v *Validation) Alpha(obj interface{}, key string) *ValidationResult {
return v.apply(Alpha{key}, obj)
}
// Test that the obj is [0-9] if type is string
func (v *Validation) Numeric(obj interface{}, key string) *ValidationResult {
return v.apply(Numeric{key}, obj)
}
// Test that the obj is [0-9a-zA-Z] if type is string
func (v *Validation) AlphaNumeric(obj interface{}, key string) *ValidationResult {
return v.apply(AlphaNumeric{key}, obj)
}
// Test that the obj matches regexp if type is string
func (v *Validation) Match(obj interface{}, regex *regexp.Regexp, key string) *ValidationResult {
return v.apply(Match{regex, key}, obj)
}
// Test that the obj doesn't match regexp if type is string
func (v *Validation) NoMatch(obj interface{}, regex *regexp.Regexp, key string) *ValidationResult {
return v.apply(NoMatch{Match{Regexp: regex}, key}, obj)
}
// Test that the obj is [0-9a-zA-Z_-] if type is string
func (v *Validation) AlphaDash(obj interface{}, key string) *ValidationResult {
return v.apply(AlphaDash{NoMatch{Match: Match{Regexp: alphaDashPattern}}, key}, obj)
}
// Test that the obj is email address if type is string
func (v *Validation) Email(obj interface{}, key string) *ValidationResult {
return v.apply(Email{Match{Regexp: emailPattern}, key}, obj)
}
// Test that the obj is IP address if type is string
func (v *Validation) IP(obj interface{}, key string) *ValidationResult {
return v.apply(IP{Match{Regexp: ipPattern}, key}, obj)
}
// Test that the obj is base64 encoded if type is string
func (v *Validation) Base64(obj interface{}, key string) *ValidationResult {
return v.apply(Base64{Match{Regexp: base64Pattern}, key}, obj)
}
// Test that the obj is chinese mobile number if type is string
func (v *Validation) Mobile(obj interface{}, key string) *ValidationResult {
return v.apply(Mobile{Match{Regexp: mobilePattern}, key}, obj)
}
// Test that the obj is chinese telephone number if type is string
func (v *Validation) Tel(obj interface{}, key string) *ValidationResult {
return v.apply(Tel{Match{Regexp: telPattern}, key}, obj)
}
// Test that the obj is chinese mobile or telephone number if type is string
func (v *Validation) Phone(obj interface{}, key string) *ValidationResult {
return v.apply(Phone{Mobile{Match: Match{Regexp: mobilePattern}},
Tel{Match: Match{Regexp: telPattern}}, key}, obj)
}
// Test that the obj is chinese zip code if type is string
func (v *Validation) ZipCode(obj interface{}, key string) *ValidationResult {
return v.apply(ZipCode{Match{Regexp: zipCodePattern}, key}, obj)
}
@ -210,6 +230,7 @@ func (v *Validation) setError(err *ValidationError) {
}
}
// Set error message for one field in ValidationError
func (v *Validation) SetError(fieldName string, errMsg string) *ValidationError {
err := &ValidationError{Key: fieldName, Field: fieldName, Tmpl: errMsg, Message: errMsg}
v.setError(err)
@ -230,6 +251,7 @@ func (v *Validation) Check(obj interface{}, checks ...Validator) *ValidationResu
return result
}
// Validate a struct.
// the obj parameter must be a struct or a struct pointer
func (v *Validation) Valid(obj interface{}) (b bool, err error) {
objT := reflect.TypeOf(obj)