github.com/zhongdalu/gf@v1.0.0/g/net/ghttp/ghttp_unit_param_struct_test.go (about)

     1  // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  package ghttp_test
     8  
     9  import (
    10  	"fmt"
    11  	"testing"
    12  	"time"
    13  
    14  	"github.com/zhongdalu/gf/g/util/gvalid"
    15  
    16  	"github.com/zhongdalu/gf/g"
    17  	"github.com/zhongdalu/gf/g/net/ghttp"
    18  	"github.com/zhongdalu/gf/g/test/gtest"
    19  )
    20  
    21  func Test_Params_Struct(t *testing.T) {
    22  	type User struct {
    23  		Id    int
    24  		Name  string
    25  		Pass1 string `params:"password1"`
    26  		Pass2 string `params:"password2" gvalid:"passwd1 @required|length:2,20|password3#||密码强度不足"`
    27  	}
    28  	p := ports.PopRand()
    29  	s := g.Server(p)
    30  	s.BindHandler("/struct1", func(r *ghttp.Request) {
    31  		if m := r.GetMap(); len(m) > 0 {
    32  			user := new(User)
    33  			r.GetToStruct(user)
    34  			r.Response.Write(user.Id, user.Name, user.Pass1, user.Pass2)
    35  		}
    36  	})
    37  	s.BindHandler("/struct2", func(r *ghttp.Request) {
    38  		if m := r.GetMap(); len(m) > 0 {
    39  			user := (*User)(nil)
    40  			r.GetToStruct(&user)
    41  			r.Response.Write(user.Id, user.Name, user.Pass1, user.Pass2)
    42  		}
    43  	})
    44  	s.BindHandler("/struct-valid", func(r *ghttp.Request) {
    45  		if m := r.GetMap(); len(m) > 0 {
    46  			user := new(User)
    47  			r.GetToStruct(user)
    48  			err := gvalid.CheckStruct(user, nil)
    49  			r.Response.Write(err.Maps())
    50  		}
    51  	})
    52  	s.SetPort(p)
    53  	s.SetDumpRouteMap(false)
    54  	s.Start()
    55  	defer s.Shutdown()
    56  
    57  	// 等待启动完成
    58  	time.Sleep(time.Second)
    59  	gtest.Case(t, func() {
    60  		client := ghttp.NewClient()
    61  		client.SetPrefix(fmt.Sprintf("http://127.0.0.1:%d", p))
    62  		gtest.Assert(client.GetContent("/struct1", `id=1&name=john&password1=123&password2=456`), `1john123456`)
    63  		gtest.Assert(client.PostContent("/struct1", `id=1&name=john&password1=123&password2=456`), `1john123456`)
    64  		gtest.Assert(client.PostContent("/struct2", `id=1&name=john&password1=123&password2=456`), `1john123456`)
    65  		gtest.Assert(client.PostContent("/struct-valid", `id=1&name=john&password1=123&password2=0`), `{"passwd1":{"length":"字段长度为2到20个字符","password3":"密码强度不足"}}`)
    66  	})
    67  }