From efe02a0355980124d39baa663b46220c1b486eaa Mon Sep 17 00:00:00 2001 From: eson <9673575+githubcontent@user.noreply.gitee.com> Date: Sun, 25 Jun 2023 11:26:47 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=20=20AuthKey=E4=B8=BA?= =?UTF-8?q?=E7=A9=BA=E7=9A=84=E6=97=B6=E5=80=99=20=E4=B9=9F=E5=8F=AF?= =?UTF-8?q?=E4=BB=A5=E8=BF=87.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- constants/webset.go | 19 +++++ goctl_template/api/context.tpl | 4 + model/gmodel/fs_web_set_logic.go | 10 ++- .../internal/svc/servicecontext.go | 4 + .../test/acceptcookielogic_test.go | 4 +- server/home-user-auth/test/basic.go | 55 +----------- .../test/useraddaddresslogic_test.go | 3 +- .../test/useraddresslistlogic_test.go | 3 +- .../test/userbasicinfologic_test.go | 3 +- .../test/userfontslogic_test.go | 3 +- .../test/usergettypelogic_test.go | 3 +- .../test/useroderdeletelogic_test.go | 3 +- .../test/usersavebasicinfologic_test.go | 3 +- .../test/userstatusconfiglogic_test.go | 3 +- .../internal/handler/wetsetsettinghandler.go | 2 +- .../internal/logic/wetsetsettinglogic.go | 85 ++++++++++--------- server/webset/internal/svc/servicecontext.go | 4 + server/webset/internal/types/types.go | 2 +- server/webset/test/basic.go | 35 ++++++++ server/webset/test/wetset_test.go | 47 ++++++++++ server_api/webset.api | 4 +- utils/basic/basic.go | 36 ++++---- utils/tests/basic.go | 57 +++++++++++++ 23 files changed, 267 insertions(+), 125 deletions(-) create mode 100644 constants/webset.go create mode 100644 server/webset/test/basic.go create mode 100644 server/webset/test/wetset_test.go create mode 100644 utils/tests/basic.go diff --git a/constants/webset.go b/constants/webset.go new file mode 100644 index 00000000..91b86149 --- /dev/null +++ b/constants/webset.go @@ -0,0 +1,19 @@ +package constants + +type TypeWebSet string + +const ( + FONT_CONFIG TypeWebSet = "font_config" //字体 + POLICY_CONFIG TypeWebSet = "policy" //政策 + CLAUSE_CONFIG TypeWebSet = "clause" //条款 + FAQ_CONFIG TypeWebSet = "faq" //问答 + RECOMMEND_DETAIL_PRODUCT TypeWebSet = "recommend_detail_" //详情页推荐-后街pid + RENDER_DESIGN TypeWebSet = "render_design_" //云渲染 后接client_no + LAST_DESIGN TypeWebSet = "last_design_" //最后设计 后接uid + OTHER_LIST TypeWebSet = "other_list_" //列表页其他列表 后接type 分类id + PRODUCT_INFO TypeWebSet = "product_info_" //详情数据 后接sn + MODEL_DATA TypeWebSet = "model_data" //所有模型数据 + TEMPLATE_PRODUCT TypeWebSet = "product_template_" //模板数据 后接产品id + CART_NUM TypeWebSet = "cart_num_" //购物车数量 后接uid + USER_ORDERNO TypeWebSet = "order_no_" //用户最新订单编号 +) diff --git a/goctl_template/api/context.tpl b/goctl_template/api/context.tpl index cc14dc4f..8a837607 100644 --- a/goctl_template/api/context.tpl +++ b/goctl_template/api/context.tpl @@ -33,6 +33,10 @@ func NewServiceContext(c {{.config}}) *ServiceContext { func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) { AuthKey := r.Header.Get("Authorization") + if AuthKey == "" { + return nil, nil + } + if len(AuthKey) <= 50 { return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey))) } diff --git a/model/gmodel/fs_web_set_logic.go b/model/gmodel/fs_web_set_logic.go index e68225aa..24092596 100644 --- a/model/gmodel/fs_web_set_logic.go +++ b/model/gmodel/fs_web_set_logic.go @@ -1,2 +1,10 @@ package gmodel -// TODO: 使用model的属性做你想做的 \ No newline at end of file + +import "context" + +// TODO: 使用model的属性做你想做的 + +func (m *FsWebSetModel) FindValueByKey(ctx context.Context, keyType string) (data FsWebSet, err error) { + err = m.db.WithContext(ctx).Model(&data).Select("value").Where("`key` = ?", keyType).Take(&data).Error + return data, err +} diff --git a/server/home-user-auth/internal/svc/servicecontext.go b/server/home-user-auth/internal/svc/servicecontext.go index d324dc9c..bcd09a0b 100644 --- a/server/home-user-auth/internal/svc/servicecontext.go +++ b/server/home-user-auth/internal/svc/servicecontext.go @@ -31,6 +31,10 @@ func NewServiceContext(c config.Config) *ServiceContext { func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) { AuthKey := r.Header.Get("Authorization") + if AuthKey == "" { + return nil, nil + } + if len(AuthKey) <= 50 { return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey))) } diff --git a/server/home-user-auth/test/acceptcookielogic_test.go b/server/home-user-auth/test/acceptcookielogic_test.go index c332af55..a7098c58 100644 --- a/server/home-user-auth/test/acceptcookielogic_test.go +++ b/server/home-user-auth/test/acceptcookielogic_test.go @@ -2,6 +2,8 @@ package logic import ( "fmt" + fstests "fusenapi/utils/tests" + "testing" "github.com/474420502/requests" @@ -14,7 +16,7 @@ func TestAcceptCookieLogic(t *testing.T) { var result gjson.Result // 获取 session,并携带 JWT token - ses := GetSesssion(t, gserver) + ses := fstests.GetSesssion() // 向服务器发送 GET 请求,获取 cookie 信息 resp, err = ses.Post(fmt.Sprintf("http://%s:%d/user/accept-cookie", cnf.Host, cnf.Port)).TestExecute(gserver) diff --git a/server/home-user-auth/test/basic.go b/server/home-user-auth/test/basic.go index 54e3630a..d47c8eae 100644 --- a/server/home-user-auth/test/basic.go +++ b/server/home-user-auth/test/basic.go @@ -6,9 +6,7 @@ import ( "fusenapi/server/home-user-auth/internal/handler" "fusenapi/server/home-user-auth/internal/svc" "log" - "testing" - "github.com/474420502/requests" "github.com/zeromicro/go-zero/core/conf" "github.com/zeromicro/go-zero/rest" ) @@ -19,10 +17,10 @@ var gserver *rest.Server func init() { log.SetFlags(log.Llongfile) - gserver = GetTestServer() + gserver = GetTestServer(testConfigFile) } -func GetTestServer() *rest.Server { +func GetTestServer(testConfigFile string) *rest.Server { conf.MustLoad(testConfigFile, &cnf) @@ -35,52 +33,3 @@ func GetTestServer() *rest.Server { fmt.Printf("Starting server at %s:%d...\n", cnf.Host, cnf.Port) return server } - -func GetSesssion(t *testing.T, server requests.ITestServer) *requests.Session { - ses := requests.NewSession() - return ses -} - -func GetSesssionWithUserToken(t *testing.T, server requests.ITestServer) *requests.Session { - ses := requests.NewSession() - tp := ses.Post(fmt.Sprintf("http://%s:%d/user/login", cnf.Host, cnf.Port)) - tp.SetBodyJson(map[string]interface{}{ - "name": "devenv@sina.cn", - "pwd": "$2y$13$6UFDMZQMEfqFYiNLpiUCi.B3fpvGEamPAjIgzUqv/u7jT05nB3pOC", - }) - resp, err := tp.TestExecute(server) - if err != nil { - t.Error(err) - } - result := resp.Json() - code := result.Get("code").Int() - if code != 200 { - t.Error("code is not 200") - } - - token := result.Get("data.token") - if !token.Exists() { - t.Error("data.token is not exists") - } - ses.Header.Add("Authorization", token.String()) - - return ses -} - -func GetSesssionWithGuestToken(t *testing.T, server requests.ITestServer) *requests.Session { - ses := requests.NewSession() - tp := ses.Post(fmt.Sprintf("http://%s:%d/accept/cookie", cnf.Host, cnf.Port)) - - resp, err := tp.TestExecute(server) - if err != nil { - t.Error(err) - } - result := resp.Json() - token := result.Get("data.token") - if !token.Exists() { - t.Error("data.token is not exists") - } - ses.Header.Add("Authorization", token.String()) - - return ses -} diff --git a/server/home-user-auth/test/useraddaddresslogic_test.go b/server/home-user-auth/test/useraddaddresslogic_test.go index 34cbce5c..813c73b2 100644 --- a/server/home-user-auth/test/useraddaddresslogic_test.go +++ b/server/home-user-auth/test/useraddaddresslogic_test.go @@ -3,6 +3,7 @@ package logic import ( "fmt" "fusenapi/server/home-user-auth/internal/types" + fstests "fusenapi/utils/tests" "testing" "github.com/474420502/requests" @@ -15,7 +16,7 @@ func TestCaseUserAddAddress(t *testing.T) { var result gjson.Result // 获取 session,并携带 JWT token - ses := GetSesssionWithUserToken(t, gserver) + ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port) // 构建新增地址请求体 addrReq := types.RequestAddAddress{ diff --git a/server/home-user-auth/test/useraddresslistlogic_test.go b/server/home-user-auth/test/useraddresslistlogic_test.go index 51b44fe7..f311d130 100644 --- a/server/home-user-auth/test/useraddresslistlogic_test.go +++ b/server/home-user-auth/test/useraddresslistlogic_test.go @@ -2,6 +2,7 @@ package logic import ( "fmt" + fstests "fusenapi/utils/tests" "testing" "github.com/474420502/requests" @@ -14,7 +15,7 @@ func TestCaseAddressList(t *testing.T) { var result gjson.Result // 获取 session,并携带 JWT token - ses := GetSesssionWithUserToken(t, gserver) + ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port) // 向服务器发送 GET 请求,获取用户地址列表 resp, err = ses.Get(fmt.Sprintf("http://%s:%d/user/address-list", cnf.Host, cnf.Port)).TestExecute(gserver) diff --git a/server/home-user-auth/test/userbasicinfologic_test.go b/server/home-user-auth/test/userbasicinfologic_test.go index f540c1dd..64863bad 100644 --- a/server/home-user-auth/test/userbasicinfologic_test.go +++ b/server/home-user-auth/test/userbasicinfologic_test.go @@ -2,6 +2,7 @@ package logic import ( "fmt" + fstests "fusenapi/utils/tests" "testing" "github.com/474420502/requests" @@ -14,7 +15,7 @@ func TestCaseBasicInfoLogic(t *testing.T) { var result gjson.Result // 获取 session,并携带 JWT token - ses := GetSesssionWithUserToken(t, gserver) + ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port) // 向服务器发送 GET 请求,获取用户基本信息 resp, err = ses.Get(fmt.Sprintf("http://%s:%d/user/basic-info", cnf.Host, cnf.Port)).TestExecute(gserver) diff --git a/server/home-user-auth/test/userfontslogic_test.go b/server/home-user-auth/test/userfontslogic_test.go index f4ce25c7..ff011b05 100644 --- a/server/home-user-auth/test/userfontslogic_test.go +++ b/server/home-user-auth/test/userfontslogic_test.go @@ -2,6 +2,7 @@ package logic import ( "fmt" + fstests "fusenapi/utils/tests" "testing" "github.com/474420502/requests" @@ -15,7 +16,7 @@ func TestCaseUserFontsLogic(t *testing.T) { var result gjson.Result // 获取 session,并携带 JWT token - ses := GetSesssionWithUserToken(t, gserver) + ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port) // 向服务器发送 GET 请求,获取字体列表 resp, err = ses.Get(fmt.Sprintf("http://%s:%d/user/fonts", cnf.Host, cnf.Port)).TestExecute(gserver) diff --git a/server/home-user-auth/test/usergettypelogic_test.go b/server/home-user-auth/test/usergettypelogic_test.go index f641397c..322e5b84 100644 --- a/server/home-user-auth/test/usergettypelogic_test.go +++ b/server/home-user-auth/test/usergettypelogic_test.go @@ -2,6 +2,7 @@ package logic import ( "fmt" + fstests "fusenapi/utils/tests" "testing" "github.com/474420502/requests" @@ -14,7 +15,7 @@ func TestCaseGetTypeLogic(t *testing.T) { var result gjson.Result // 获取 session,并携带 JWT token - ses := GetSesssionWithUserToken(t, gserver) + ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port) // 向服务器发送 GET 请求,获取用户类型信息 resp, err = ses.Get(fmt.Sprintf("http://%s:%d/user/get-type", cnf.Host, cnf.Port)).TestExecute(gserver) diff --git a/server/home-user-auth/test/useroderdeletelogic_test.go b/server/home-user-auth/test/useroderdeletelogic_test.go index fb46bfed..79bf80a8 100644 --- a/server/home-user-auth/test/useroderdeletelogic_test.go +++ b/server/home-user-auth/test/useroderdeletelogic_test.go @@ -3,6 +3,7 @@ package logic import ( "fmt" "fusenapi/server/home-user-auth/internal/types" + fstests "fusenapi/utils/tests" "testing" "github.com/474420502/requests" @@ -15,7 +16,7 @@ func TestCaseLogic(t *testing.T) { var result gjson.Result // 获取 session,并携带 JWT token - ses := GetSesssionWithUserToken(t, gserver) + ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port) // 向服务器发送 GET 请求,获取用户类型信息 tp := ses.Post(fmt.Sprintf("http://%s:%d/user/order-delete", cnf.Host, cnf.Port)) diff --git a/server/home-user-auth/test/usersavebasicinfologic_test.go b/server/home-user-auth/test/usersavebasicinfologic_test.go index 43dae165..42e3160a 100644 --- a/server/home-user-auth/test/usersavebasicinfologic_test.go +++ b/server/home-user-auth/test/usersavebasicinfologic_test.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "fusenapi/server/home-user-auth/internal/types" + fstests "fusenapi/utils/tests" "testing" "github.com/474420502/requests" @@ -16,7 +17,7 @@ func TestCaseUserSaveBasicinfoLogic(t *testing.T) { var result gjson.Result // 获取 session,并携带 JWT token - ses := GetSesssionWithUserToken(t, gserver) + ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port) var tp *requests.Temporary tp = ses.Get(fmt.Sprintf("http://%s:%d/user/basic-info", cnf.Host, cnf.Port)) diff --git a/server/home-user-auth/test/userstatusconfiglogic_test.go b/server/home-user-auth/test/userstatusconfiglogic_test.go index 7578f1c1..e6336d7f 100644 --- a/server/home-user-auth/test/userstatusconfiglogic_test.go +++ b/server/home-user-auth/test/userstatusconfiglogic_test.go @@ -2,6 +2,7 @@ package logic import ( "fmt" + fstests "fusenapi/utils/tests" "testing" "github.com/474420502/requests" @@ -14,7 +15,7 @@ func TestCaseUserStatusConfigLogic(t *testing.T) { var result gjson.Result // 获取 session,并携带 JWT token - ses := GetSesssionWithUserToken(t, gserver) + ses := fstests.GetSesssionWithUserToken(t, gserver, cnf.Host, cnf.Port) // 向服务器发送 GET 请求,获取用户类型信息 resp, err = ses.Post(fmt.Sprintf("http://%s:%d/user/status-config", cnf.Host, cnf.Port)).TestExecute(gserver) diff --git a/server/webset/internal/handler/wetsetsettinghandler.go b/server/webset/internal/handler/wetsetsettinghandler.go index 2e843a97..8c080435 100644 --- a/server/webset/internal/handler/wetsetsettinghandler.go +++ b/server/webset/internal/handler/wetsetsettinghandler.go @@ -53,7 +53,7 @@ func WetSetSettingHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { userinfo = &auth.UserInfo{UserId: 0, GuestId: 0} } - var req types.RequestFaq + var req types.RequestWebSet // 如果端点有请求结构体,则使用httpx.Parse方法从HTTP请求体中解析请求数据 if err := httpx.Parse(r, &req); err != nil { httpx.OkJsonCtx(r.Context(), w, &basic.Response{ diff --git a/server/webset/internal/logic/wetsetsettinglogic.go b/server/webset/internal/logic/wetsetsettinglogic.go index 00a2ec50..68556769 100644 --- a/server/webset/internal/logic/wetsetsettinglogic.go +++ b/server/webset/internal/logic/wetsetsettinglogic.go @@ -1,6 +1,7 @@ package logic import ( + "encoding/json" "fusenapi/constants" "fusenapi/utils/auth" "fusenapi/utils/basic" @@ -29,53 +30,57 @@ func NewWetSetSettingLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Wet } } -var TagTexts = map[int]map[string]string{ - 1: {"title": "order", "icon": "faq/order.png", "icon_name": "orders"}, - 2: {"title": "Shipping", "icon": "faq/shipping.png", "icon_name": "delivery"}, - 3: {"title": "Payment", "icon": "faq/payment.png", "icon_name": "wallet"}, - 4: {"title": "Return", "icon": "faq/return.png", "icon_name": "freight"}, -} - -func (l *WetSetSettingLogic) WetSetSetting(req *types.RequestFaq, userinfo *auth.UserInfo) (resp *basic.Response) { +func (l *WetSetSettingLogic) WetSetSetting(req *types.RequestWebSet, userinfo *auth.UserInfo) (resp *basic.Response) { // 返回值必须调用Set重新返回, resp可以空指针调用 resp.SetStatus(basic.CodeOK, data) // userinfo 传入值时, 一定不为null - switch req.Type { - case "faq": + typeConf := constants.TypeWebSet(req.Type) - result := make(map[string]interface{}) - result["title"] = "Common Problem" - result["introduction"] = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout." - - lists := make([]map[string]interface{}, 0) - for tagID, tagText := range TagTexts { - faqs, err := l.svcCtx.AllModels.FsFaq.FindOneByTagId(l.ctx, tagID, int64(constants.STATUS_ON)) - if err == gorm.ErrRecordNotFound { - return resp.SetStatus(basic.CodeDbRecordNotFoundErr) - } - - // items := getFaqItems(tagID) - for k, item := range items { - content := strings.Split(item.Content, "\n") - items[k].Content = content - } - - res := make(map[string]interface{}) - res["title"] = tagText["title"] - res["icon"] = tagText["icon"] - res["icon_name"] = tagText["icon_name"] - res["items"] = items - - lists = append(lists, res) + //如果是这三个配置项 则读取缓存 + var result map[string]interface{} + data, err := l.svcCtx.AllModels.FsWebSet.FindValueByKey(l.ctx, string(typeConf)) + if err != nil { + if err == gorm.ErrRecordNotFound { + return resp.SetStatus(basic.CodeDbRecordNotFoundErr) } - result["list"] = lists - - return resp.SetStatus(basic.CodeOK, result) - case "clause": - case "policy": - default: return resp.SetStatus(basic.CodeDbSqlErr) } + //读取配置项 + err = json.Unmarshal([]byte(*data.Value), &result) + if err != nil { + return resp.SetStatus(basic.CodeJsonErr) + } + //组装配置项的内容数据 + for k, v := range result["list"].(map[string]interface{}) { + //按空格分隔内容 + result["list"].(map[string]interface{})[k].(map[string]interface{})["content"] = strings.Split(v.(string), "\n") + } + + // TODO: 缓存 + if typeConf == constants.CLAUSE_CONFIG || typeConf == constants.FAQ_CONFIG || typeConf == constants.POLICY_CONFIG { + // cache := redis.NewClient(&redis.Options{ + // Addr: "localhost:6379", + // Password: "", // no password set + // DB: 0, // use default DB + // }) + // if cache.Exists(ctx.Query("type")).Val() > 0 { + // result = cache.HGetAll(ctx.Query("type")).Val() + // } else { + // //读取配置项 + // model := WebSet{Key: typeStr} + // db.First(&model) + // result = json.Unmarshal([]byte(model.Value), &result) + // //组装配置项的内容数据 + // for k, v := range result["list"].(map[string]interface{}) { + // //按空格分隔内容 + // result["list"].(map[string]interface{})[k].(map[string]interface{})["content"] = strings.Split(v.(string), "\n") + // } + // cache.HMSet(ctx.Query("type"), result) + // } + } else { + + } + return resp.SetStatus(basic.CodeOK) } diff --git a/server/webset/internal/svc/servicecontext.go b/server/webset/internal/svc/servicecontext.go index 291cebf9..dac5a5fd 100644 --- a/server/webset/internal/svc/servicecontext.go +++ b/server/webset/internal/svc/servicecontext.go @@ -31,6 +31,10 @@ func NewServiceContext(c config.Config) *ServiceContext { func (svcCtx *ServiceContext) ParseJwtToken(r *http.Request) (jwt.MapClaims, error) { AuthKey := r.Header.Get("Authorization") + if AuthKey == "" { + return nil, nil + } + if len(AuthKey) <= 50 { return nil, errors.New(fmt.Sprint("Error parsing token, len:", len(AuthKey))) } diff --git a/server/webset/internal/types/types.go b/server/webset/internal/types/types.go index 2674ac6f..f063c69f 100644 --- a/server/webset/internal/types/types.go +++ b/server/webset/internal/types/types.go @@ -5,7 +5,7 @@ import ( "fusenapi/utils/basic" ) -type RequestFaq struct { +type RequestWebSet struct { Type string `form:"type"` } diff --git a/server/webset/test/basic.go b/server/webset/test/basic.go new file mode 100644 index 00000000..34dbd613 --- /dev/null +++ b/server/webset/test/basic.go @@ -0,0 +1,35 @@ +package logic + +import ( + "fmt" + "fusenapi/server/webset/internal/config" + "fusenapi/server/webset/internal/handler" + "fusenapi/server/webset/internal/svc" + "log" + + "github.com/zeromicro/go-zero/core/conf" + "github.com/zeromicro/go-zero/rest" +) + +var testConfigFile = "../etc/wetset.yaml" +var cnf config.Config +var gserver *rest.Server + +func init() { + log.SetFlags(log.Llongfile) + gserver = GetTestServer(testConfigFile) +} + +func GetTestServer(testConfigFile string) *rest.Server { + + conf.MustLoad(testConfigFile, &cnf) + + server := rest.MustNewServer(cnf.RestConf) + defer server.Stop() + + ctx := svc.NewServiceContext(cnf) + handler.RegisterHandlers(server, ctx) + + fmt.Printf("Starting server at %s:%d...\n", cnf.Host, cnf.Port) + return server +} diff --git a/server/webset/test/wetset_test.go b/server/webset/test/wetset_test.go new file mode 100644 index 00000000..1ce43b54 --- /dev/null +++ b/server/webset/test/wetset_test.go @@ -0,0 +1,47 @@ +package logic + +import ( + "fmt" + fstests "fusenapi/utils/tests" + "log" + "testing" + + "github.com/474420502/requests" + "github.com/tidwall/gjson" +) + +func TestWetSetLogic(t *testing.T) { + var err error + var resp *requests.Response + var result gjson.Result + + // 获取 session,并携带 JWT token + ses := fstests.GetSesssion() + // 向服务器发送 GET 请求,获取 cookie 信息 + resp, err = ses.Get(fmt.Sprintf("http://%s:%d/wet-set/setting", cnf.Host, cnf.Port)).TestExecute(gserver) + if err != nil { + t.Error(err) + } + + // 使用 gjson 解析返回的 json 数据 + result = resp.Json() // gjson + + log.Println(result) + // 检查返回值中的 code 字段是否存在,并且值是否为 200 + code := result.Get("code").Int() + if code != 200 { + t.Errorf("Invalid code value: %d", code) + } + + // 检查返回值中的 msg 字段是否存在,并且值是否为 "success" + msg := result.Get("msg").String() + if msg != "success" { + t.Errorf(`Invalid msg value: "%s"`, msg) + } + + // 检查返回值中的 data 字段是否存在,并且值是否符合预期 + token := result.Get("data.token").String() + if len(token) == 0 { + t.Error("Missing token field") + } +} diff --git a/server_api/webset.api b/server_api/webset.api index ee93a856..2bb41ded 100644 --- a/server_api/webset.api +++ b/server_api/webset.api @@ -11,10 +11,10 @@ import "basic.api" service wetset { @handler WetSetSettingHandler - get /web-set/setting(RequestFaq) returns (response); + get /web-set/setting(RequestWebSet) returns (response); } -type RequestFaq { +type RequestWebSet { Type string `form:"type"` } diff --git a/utils/basic/basic.go b/utils/basic/basic.go index 15726e88..23f8c8c0 100644 --- a/utils/basic/basic.go +++ b/utils/basic/basic.go @@ -9,32 +9,32 @@ type StatusResponse struct { var ( CodeOK = &StatusResponse{200, "success"} // 成功 CodeApiErr = &StatusResponse{500, "api error"} // API错误 - CodeSaveErr = &StatusResponse{501, "fail to save"} // 保存失败 + CodeSaveErr = &StatusResponse{501, "failed to save"} // 保存失败 CodeServiceErr = &StatusResponse{510, "server logic error"} // 服务逻辑错误 CodeUnAuth = &StatusResponse{401, "unauthorized"} // 未授权 - CodeEmailNotFoundErr = &StatusResponse{5050, "the email was not found"} // 未找到email - CodeUserIdNotFoundErr = &StatusResponse{5051, "the user was not found"} // 未找到用户 - CodePasswordErr = &StatusResponse{5052, "invalid password"} // 无效密码 + CodeEmailNotFoundErr = &StatusResponse{5050, "email not found"} // 未找到email + CodeUserIdNotFoundErr = &StatusResponse{5051, "user not found"} // 未找到用户 + CodePasswordErr = &StatusResponse{5052, "invalid password"} // 无效密码 - CodeSafeValueRangeErr = &StatusResponse{5040, "the value was not in values"} // 值不在范围内 + CodeSafeValueRangeErr = &StatusResponse{5040, "value not in range"} // 值不在范围内 - CodeOrderNotFoundErr = &StatusResponse{5030, "the order not found"} //未找到订单 - CodeOrderNotCancelledErr = &StatusResponse{5031, "The current order cannot be cancelled"} // 当前订单无法取消 + CodeOrderNotFoundErr = &StatusResponse{5030, "order not found"} //未找到订单 + CodeOrderNotCancelledErr = &StatusResponse{5031, "current order cannot be cancelled"} // 当前订单无法取消 - CodePayNotFoundErr = &StatusResponse{5020, "The pay not found"} // 支付信息无法查询 - CodePayCancelOk = &StatusResponse{5021, "Cancel successfully"} // 支付取消 - CodePayCancelNotOk = &StatusResponse{5022, "Cancel failure"} // 支付取消 + CodePayNotFoundErr = &StatusResponse{5020, "pay info not found"} // 支付信息无法查询 + CodePayCancelOk = &StatusResponse{5021, "cancellation successful"} // 支付取消成功 + CodePayCancelNotOk = &StatusResponse{5022, "cancellation failed"} // 支付取消失败 - CodeGuestDupErr = &StatusResponse{5010, "the user is already a guest user and does not need to apply again"} // 用户已经是访客用户,不需要重复申请 - CodeGuestGenErr = &StatusResponse{5011, "serialization failed for guest_id of the visitor"} // 访客ID序列化失败 + CodeGuestDupErr = &StatusResponse{5010, "user is already guest and does not need to reapply"} // 用户已经是访客用户,无需重复申请 + CodeGuestGenErr = &StatusResponse{5011, "serialization failed for guest ID"} // 访客ID序列化失败 - CodeDbUpdateErr = &StatusResponse{5000, "update database error"} // 数据库更新错误 - // 5001 - CodeRequestParamsErr = &StatusResponse{5002, "invalid request param"} // 请求参数无效 - CodeDbRecordNotFoundErr = &StatusResponse{5003, "db record not found"} //未在数据库中找到记录 - CodeDbCreateErr = &StatusResponse{5004, "create one in database error"} // 在数据库中创建错误 - CodeDbSqlErr = &StatusResponse{5005, "database is error"} // 数据库错误 + CodeDbUpdateErr = &StatusResponse{5000, "database update error"} // 数据库更新错误 + CodeRequestParamsErr = &StatusResponse{5002, "invalid request parameters"} // 请求参数无效 + CodeDbRecordNotFoundErr = &StatusResponse{5003, "database record not found"} //数据库中未找到记录 + CodeDbCreateErr = &StatusResponse{5004, "failed to create record in database"} // 数据库中创建记录失败 + CodeDbSqlErr = &StatusResponse{5005, "database error"} // 数据库错误 + CodeJsonErr = &StatusResponse{5006, "JSON error"} // JSON解析错误 ) type Response struct { diff --git a/utils/tests/basic.go b/utils/tests/basic.go new file mode 100644 index 00000000..b4c2e73b --- /dev/null +++ b/utils/tests/basic.go @@ -0,0 +1,57 @@ +package fstests + +import ( + "fmt" + "testing" + + "github.com/474420502/requests" +) + +func GetSesssion() *requests.Session { + ses := requests.NewSession() + return ses +} + +func GetSesssionWithUserToken(t *testing.T, server requests.ITestServer, Host string, Port int) *requests.Session { + ses := requests.NewSession() + tp := ses.Post(fmt.Sprintf("http://%s:%d/user/login", Host, Port)) + tp.SetBodyJson(map[string]interface{}{ + "name": "devenv@sina.cn", + "pwd": "$2y$13$6UFDMZQMEfqFYiNLpiUCi.B3fpvGEamPAjIgzUqv/u7jT05nB3pOC", + }) + resp, err := tp.TestExecute(server) + if err != nil { + t.Error(err) + } + result := resp.Json() + code := result.Get("code").Int() + if code != 200 { + t.Error("code is not 200") + } + + token := result.Get("data.token") + if !token.Exists() { + t.Error("data.token is not exists") + } + ses.Header.Add("Authorization", token.String()) + + return ses +} + +func GetSesssionWithGuestToken(t *testing.T, server requests.ITestServer, Host string, Port int) *requests.Session { + ses := requests.NewSession() + tp := ses.Post(fmt.Sprintf("http://%s:%d/accept/cookie", Host, Port)) + + resp, err := tp.TestExecute(server) + if err != nil { + t.Error(err) + } + result := resp.Json() + token := result.Get("data.token") + if !token.Exists() { + t.Error("data.token is not exists") + } + ses.Header.Add("Authorization", token.String()) + + return ses +}