github.com/godaddy-x/freego@v1.0.156/node/test/webapp.go (about)

     1  package http_web
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/godaddy-x/freego/ex"
     6  	"github.com/godaddy-x/freego/geetest"
     7  	"github.com/godaddy-x/freego/node"
     8  	"github.com/godaddy-x/freego/node/common"
     9  	"github.com/godaddy-x/freego/rpcx"
    10  	"github.com/godaddy-x/freego/rpcx/pb"
    11  	"github.com/godaddy-x/freego/utils"
    12  	"github.com/godaddy-x/freego/utils/crypto"
    13  	"github.com/godaddy-x/freego/utils/jwt"
    14  	"github.com/godaddy-x/freego/utils/sdk"
    15  )
    16  
    17  type MyWebNode struct {
    18  	node.HttpNode
    19  }
    20  
    21  type GetUserReq struct {
    22  	common.BaseReq
    23  	Uid  int    `json:"uid"`
    24  	Name string `json:"name"`
    25  }
    26  
    27  func (self *MyWebNode) test(ctx *node.Context) error {
    28  	req := &GetUserReq{}
    29  	if err := ctx.Parser(req); err != nil {
    30  		return err
    31  	}
    32  	//return self.Html(ctx, "/resource/index.html", map[string]interface{}{"tewt": 1})
    33  	return self.Json(ctx, map[string]interface{}{"test": 1})
    34  	//return ex.Throw{Code: ex.BIZ, Msg: "测试错误"}
    35  }
    36  
    37  func (self *MyWebNode) getUser(ctx *node.Context) error {
    38  	req := &GetUserReq{}
    39  	if err := ctx.Parser(req); err != nil {
    40  		return err
    41  	}
    42  	return self.Json(ctx, map[string]interface{}{"test": "我爱中国+-/+_=/1df"})
    43  }
    44  
    45  func testCallRPC() {
    46  	conn, err := rpcx.NewClientConn(rpcx.GRPC{Service: "PubWorker", Cache: 30})
    47  	if err != nil {
    48  		fmt.Println(err)
    49  		return
    50  	}
    51  	defer conn.Close()
    52  	res, err := pb.NewPubWorkerClient(conn.Value()).GenerateId(conn.Context(), &pb.GenerateIdReq{})
    53  	if err != nil {
    54  		fmt.Println(err)
    55  		return
    56  	}
    57  	fmt.Println("call rpc:", res)
    58  }
    59  
    60  func (self *MyWebNode) login(ctx *node.Context) error {
    61  	//fmt.Println("-----", ctx.GetHeader("Language"))
    62  	//fmt.Println("-----", ctx.GetPostBody())
    63  	//// {"test":"测试$1次 我是$4岁"}
    64  	//return ex.Throw{Msg: "${test}", Arg: []string{"1", "2", "123", "99"}}
    65  	//self.LoginBySubject(subject, exp)
    66  	config := ctx.GetJwtConfig()
    67  	token := ctx.Subject.Create(utils.NextSID()).Dev("APP").Generate(config)
    68  	secret := jwt.GetTokenSecret(token, config.TokenKey)
    69  	return self.Json(ctx, &sdk.AuthToken{
    70  		Token:   token,
    71  		Secret:  secret,
    72  		Expired: ctx.Subject.Payload.Exp,
    73  	})
    74  	//return self.Html(ctx, "/web/index.html", map[string]interface{}{"tewt": 1})
    75  }
    76  
    77  func (self *MyWebNode) publicKey(ctx *node.Context) error {
    78  	//testCallRPC()
    79  	_, publicKey := ctx.RSA.GetPublicKey()
    80  	return self.Text(ctx, publicKey)
    81  }
    82  
    83  func (self *MyWebNode) testGuestPost(ctx *node.Context) error {
    84  	fmt.Println(string(ctx.JsonBody.RawData()))
    85  	return self.Json(ctx, map[string]string{"res": "中文测试下Guest响应"})
    86  }
    87  
    88  func (self *MyWebNode) testHAX(ctx *node.Context) error {
    89  	fmt.Println(string(ctx.JsonBody.RawData()))
    90  	return self.Json(ctx, map[string]string{"res": "中文测试下HAX响应"})
    91  }
    92  
    93  func (self *MyWebNode) FirstRegister(ctx *node.Context) error {
    94  	res, err := geetest.FirstRegister(ctx)
    95  	if err != nil {
    96  		return err
    97  	}
    98  	return self.Json(ctx, res)
    99  }
   100  
   101  func (self *MyWebNode) SecondValidate(ctx *node.Context) error {
   102  	res, err := geetest.SecondValidate(ctx)
   103  	if err != nil {
   104  		return err
   105  	}
   106  	return self.Json(ctx, res)
   107  }
   108  
   109  type NewPostFilter struct{}
   110  
   111  func (self *NewPostFilter) DoFilter(chain node.Filter, ctx *node.Context, args ...interface{}) error {
   112  	//fmt.Println(" --- NewFilter.DoFilter before ---")
   113  	ctx.AddStorage("httpLog", node.HttpLog{Method: ctx.Path, LogNo: utils.NextSID(), CreateAt: utils.UnixMilli()})
   114  	if err := chain.DoFilter(chain, ctx, args...); err != nil {
   115  		return err
   116  	}
   117  	//fmt.Println(" --- NewFilter.DoFilter after ---")
   118  	v := ctx.GetStorage("httpLog")
   119  	if v == nil {
   120  		return utils.Error("httpLog is nil")
   121  	}
   122  	httpLog, _ := v.(node.HttpLog)
   123  	httpLog.UpdateAt = utils.UnixMilli()
   124  	httpLog.CostMill = httpLog.UpdateAt - httpLog.CreateAt
   125  	//zlog.Info("http log", 0, zlog.Any("data", httpLog))
   126  	return nil
   127  }
   128  
   129  type GeetestFilter struct{}
   130  
   131  func (self *GeetestFilter) DoFilter(chain node.Filter, ctx *node.Context, args ...interface{}) error {
   132  	// TODO 读取自定义需要拦截的方法名+手机号码或账号
   133  	username := utils.GetJsonString(ctx.JsonBody.RawData(), "username")
   134  	filterObject := geetest.CreateFilterObject(ctx.Method, username)
   135  	if !geetest.ValidSuccess(filterObject) {
   136  		return utils.Error("geetest invalid")
   137  	}
   138  	if err := chain.DoFilter(chain, ctx, args...); err != nil {
   139  		return err
   140  	}
   141  	return geetest.CleanStatus(filterObject)
   142  }
   143  
   144  type TestFilter struct{}
   145  
   146  func (self *TestFilter) DoFilter(chain node.Filter, ctx *node.Context, args ...interface{}) error {
   147  	ctx.Json(map[string]string{"tttt": "22222"})
   148  	//return utils.Error("11111")
   149  	return chain.DoFilter(chain, ctx, args...)
   150  }
   151  
   152  const (
   153  	privateKey = "MHcCAQEEIEpXwxicdbb4DM+EW/cJVvoTSubRHIKB6kai/1qgaWnNoAoGCCqGSM49AwEHoUQDQgAEo2hpVqkCUrLC/mxd9qD8sdryanqx0YVfpAfN9ciMGiOSgJ8KBmDpE8FfAtRSk8PM4Le6EMLrQQLPaLURshOwZg=="
   154  )
   155  
   156  func roleRealm(ctx *node.Context, onlyRole bool) (*node.Permission, error) {
   157  	permission := &node.Permission{}
   158  	if onlyRole {
   159  		permission.HasRole = []int64{1, 2, 3, 4}
   160  		return permission, nil
   161  	}
   162  	//permission.Ready = true
   163  	//permission.MatchAll = true
   164  	permission.NeedRole = []int64{2, 3, 4}
   165  	return permission, nil
   166  }
   167  
   168  func NewHTTP() *MyWebNode {
   169  	var my = &MyWebNode{}
   170  	my.EnableECC(true)
   171  	my.AddJwtConfig(jwt.JwtConfig{
   172  		TokenTyp: jwt.JWT,
   173  		TokenAlg: jwt.HS256,
   174  		TokenKey: "123456" + utils.CreateLocalSecretKey(12, 45, 23, 60, 58, 30),
   175  		TokenExp: jwt.TWO_WEEK,
   176  	})
   177  	cipher := &crypto.EccObj{}
   178  	if err := cipher.LoadS256ECC(privateKey); err != nil {
   179  		panic("ECC certificate generation failed")
   180  	}
   181  	my.AddCipher(cipher)
   182  	//my.AddCache(func(ds ...string) (cache.Cache, error) {
   183  	//	rds, err := cache.NewRedis(ds...)
   184  	//	return rds, err
   185  	//})
   186  	my.SetSystem("test", "1.0.0")
   187  	my.AddRoleRealm(roleRealm)
   188  	my.AddErrorHandle(func(ctx *node.Context, throw ex.Throw) error {
   189  		fmt.Println(throw)
   190  		return throw
   191  	})
   192  	my.AddFilter(&node.FilterObject{Name: "TestFilter", Order: 100, Filter: &TestFilter{}, MatchPattern: []string{"/getUser"}})
   193  	my.AddFilter(&node.FilterObject{Name: "NewPostFilter", Order: 100, Filter: &NewPostFilter{}})
   194  	my.AddFilter(&node.FilterObject{Name: "GeetestFilter", Order: 101, MatchPattern: []string{"/TestGeetest"}, Filter: &GeetestFilter{}})
   195  	return my
   196  }
   197  
   198  func StartHttpNode() {
   199  	go geetest.CheckServerStatus(geetest.Config{})
   200  	my := NewHTTP()
   201  	my.POST("/test1", my.test, nil)
   202  	my.POST("/getUser", my.getUser, nil)
   203  	my.POST("/testGuestPost", my.testGuestPost, &node.RouterConfig{Guest: true})
   204  	my.POST("/testHAX", my.testHAX, &node.RouterConfig{UseHAX: true})
   205  	my.GET("/key", my.publicKey, &node.RouterConfig{Guest: true})
   206  	my.POST("/login", my.login, &node.RouterConfig{UseRSA: true})
   207  
   208  	my.POST("/geetest/register", my.FirstRegister, &node.RouterConfig{UseRSA: true})
   209  	my.POST("/geetest/validate", my.SecondValidate, &node.RouterConfig{UseRSA: true})
   210  
   211  	my.AddLanguageByJson("en", []byte(`{"test":"测试$1次 我是$4岁"}`))
   212  	my.StartServer(":8090")
   213  }
   214  
   215  func StartHttpNode1() {
   216  	go geetest.CheckServerStatus(geetest.Config{})
   217  	my := NewHTTP()
   218  	my.POST("/test1", my.test, nil)
   219  	my.StartServer(":8091")
   220  }
   221  
   222  func StartHttpNode2() {
   223  	go geetest.CheckServerStatus(geetest.Config{})
   224  	my := NewHTTP()
   225  	my.POST("/test1", my.test, nil)
   226  	my.StartServer(":8092")
   227  }