Browse Source

add:report

zqbao 11 months ago
parent
commit
5edc63c88b

+ 3 - 0
conf/app.conf

@@ -5,3 +5,6 @@ autorender = false
 copyrequestbody = true
 EnableDocs = true
 sqlconn = 
+
+eta_mini_api_appid = "tubmafwrzhpgfiuf"
+eta_mini_api_secret = "eotpcqbvhycdshwscqnytiwzbgonposs"

+ 144 - 0
controllers/base_auth.go

@@ -0,0 +1,144 @@
+package controllers
+
+import (
+	"encoding/json"
+	"eta/eta_mini_bridge/models"
+	"eta/eta_mini_bridge/utils"
+	"fmt"
+	"net/http"
+	"net/url"
+
+	"github.com/beego/beego/v2/server/web"
+)
+
+type BaseAuthController struct {
+	web.Controller
+	Token string
+}
+
+func (this *BaseAuthController) Prepare() {
+	method := this.Ctx.Input.Method()
+	uri := this.Ctx.Input.URI()
+	fmt.Println("Url:", uri)
+
+	header := this.Ctx.Request.Header
+	headerBody, err := json.Marshal(header)
+	fmt.Println(err)
+	fmt.Println("header:" + string(headerBody))
+
+	if method != "HEAD" {
+		//校验签名
+		nonce := this.Ctx.Input.Header("Nonce")
+		timestamp := this.Ctx.Input.Header("Timestamp")
+		appid := this.Ctx.Input.Header("Appid")
+		signature := this.Ctx.Input.Header("Signature")
+
+		if nonce == "" {
+			errMsg := "随机字符串不能为空"
+			this.JSON(models.BaseResponse{Ret: 400, Msg: "", ErrMsg: errMsg}, false, false)
+			this.StopRun()
+			return
+		}
+
+		if timestamp == "" {
+			errMsg := "时间戳不能为空"
+			this.JSON(models.BaseResponse{Ret: 400, Msg: "", ErrMsg: errMsg}, false, false)
+			this.StopRun()
+			return
+		}
+
+		checkSign := utils.GetSign(nonce, timestamp, appid, utils.ETA_MINI_API_SECRET)
+		if signature != checkSign {
+			errMsg := "签名错误"
+			this.JSON(models.BaseResponse{Ret: 401, Msg: "", ErrMsg: errMsg}, false, false)
+			this.StopRun()
+			return
+		}
+		if method != "GET" && method != "POST" {
+			errMsg := "无效的请求方式"
+			this.JSON(models.BaseResponse{Ret: 501, Msg: "", ErrMsg: errMsg}, false, false)
+			this.StopRun()
+			return
+		}
+	} else {
+		this.JSON(models.BaseResponse{Ret: 500, Msg: "系统异常,请联系客服!", ErrMsg: "method:" + method}, false, false)
+		this.StopRun()
+		return
+	}
+}
+
+func (c *BaseAuthController) ServeJSON(encoding ...bool) {
+	//所有请求都做这么个处理吧,目前这边都是做编辑、刷新逻辑处理(新增的话,并没有指标id,不会有影响)
+	var (
+		hasIndent   = false
+		hasEncoding = false
+	)
+	if web.BConfig.RunMode == web.PROD {
+		hasIndent = false
+	}
+	if len(encoding) > 0 && encoding[0] == true {
+		hasEncoding = true
+	}
+	if c.Data["json"] == nil {
+		//go utils.SendEmail("异常提醒:", "接口:"+"URI:"+c.Ctx.Input.URI()+";无返回值", utils.EmailSendToUsers)
+		//body := "接口:" + "URI:" + c.Ctx.Input.URI() + ";无返回值"
+		//go alarm_msg.SendAlarmMsg(body, 1)
+		return
+	}
+
+	baseRes := c.Data["json"].(*models.BaseResponse)
+	if baseRes != nil && baseRes.Ret != 408 {
+		//body, _ := json.Marshal(baseRes)
+		//var requestBody string
+		//method := c.Ctx.Input.Method()
+		//if method == "GET" {
+		//	requestBody = c.Ctx.Request.RequestURI
+		//} else {
+		//	requestBody, _ = url.QueryUnescape(string(c.Ctx.Input.RequestBody))
+		//}
+		//if baseRes.Ret != 200 && baseRes.IsSendEmail {
+		//	go utils.SendEmail(utils.APP_NAME_CN+"【"+utils.RunMode+"】"+"失败提醒", "URI:"+c.Ctx.Input.URI()+"<br/> "+"Params"+requestBody+" <br/>"+"ErrMsg:"+baseRes.ErrMsg+";<br/>Msg:"+baseRes.Msg+";<br/> Body:"+string(body)+"<br/>", utils.EmailSendToUsers)
+		//}
+
+		// 记录错误日志, 并清掉错误信息避免暴露给外部
+		if baseRes.ErrMsg != "" {
+
+			utils.FileLog.Info(baseRes.ErrMsg)
+			baseRes.ErrMsg = ""
+		}
+	}
+	c.JSON(c.Data["json"], hasIndent, hasEncoding)
+}
+
+func (c *BaseAuthController) JSON(data interface{}, hasIndent bool, coding bool) error {
+	c.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
+	var content []byte
+	var err error
+	if hasIndent {
+		content, err = json.MarshalIndent(data, "", "  ")
+	} else {
+		content, err = json.Marshal(data)
+	}
+	if err != nil {
+		http.Error(c.Ctx.Output.Context.ResponseWriter, err.Error(), http.StatusInternalServerError)
+		return err
+	}
+	ip := c.Ctx.Input.IP()
+	requestBody, err := url.QueryUnescape(string(c.Ctx.Input.RequestBody))
+	if err != nil {
+		requestBody = string(c.Ctx.Input.RequestBody)
+	}
+	if requestBody == "" {
+		requestBody = c.Ctx.Input.URI()
+	}
+	c.logUri(data, requestBody, ip)
+	if coding {
+		content = []byte(utils.StringsToJSON(string(content)))
+	}
+	return c.Ctx.Output.Body(content)
+}
+
+func (c *BaseAuthController) logUri(respContent interface{}, requestBody, ip string) {
+	utils.ApiLog.Info("uri:%s,  requestBody:%s, responseBody:%s, ip:%s", c.Ctx.Input.URI(), requestBody, respContent, ip)
+	return
+}

+ 70 - 0
controllers/report.go

@@ -0,0 +1,70 @@
+package controllers
+
+import (
+	"eta/eta_mini_bridge/models"
+	"eta/eta_mini_bridge/models/response"
+	"eta/eta_mini_bridge/utils"
+
+	"github.com/rdlucklib/rdluck_tools/paging"
+)
+
+type ReportController struct {
+	BaseAuthController
+}
+
+// @Title CreateUser
+// @Description create users
+// @Param	body		body 	models.User	true		"body for user content"
+// @Success 200 {int} models.User.Id
+// @Failure 403 body is empty
+// @router /list [get]
+func (this *ReportController) List() {
+	br := new(models.BaseResponse).Init()
+	defer func() {
+		this.Data["json"] = br
+		this.ServeJSON()
+	}()
+
+	userId, _ := this.GetInt("UserId")
+	pageSize, _ := this.GetInt("PageSize")
+	currentIndex, _ := this.GetInt("CurrentIndex")
+	classifyId, _ := this.GetInt("ClassifyId")
+	if classifyId <= 0 {
+		br.Msg = "参数错误"
+		br.ErrMsg = "参数错误,分类id小于等于0"
+		return
+	}
+
+	var startSize int
+	if pageSize <= 0 {
+		pageSize = utils.PageSize20
+	}
+	if currentIndex <= 0 {
+		currentIndex = 1
+	}
+	startSize = utils.StartIndex(currentIndex, pageSize)
+
+	total, err := models.GetReportListCount(classifyId)
+	if err != nil {
+		br.Msg = "获取数据失败"
+		br.ErrMsg = "获取数据失败,Err:" + err.Error()
+		return
+	}
+
+	list, err := models.GetReportList(classifyId, startSize, pageSize)
+	if err != nil {
+		br.Msg = "获取失败"
+		br.ErrMsg = "获取失败,Err:" + err.Error()
+		return
+	}
+	page := paging.GetPaging(currentIndex, pageSize, total)
+
+	resp := new(response.ReportListResp)
+	resp.Paging = page
+	resp.List = list
+
+	br.Ret = 200
+	br.Success = true
+	br.Msg = "获取成功"
+	br.Data = resp
+}

+ 0 - 119
controllers/user.go

@@ -1,119 +0,0 @@
-package controllers
-
-import (
-	"eta/eta_mini_bridge/models"
-	"encoding/json"
-
-	beego "github.com/beego/beego/v2/server/web"
-)
-
-// Operations about Users
-type UserController struct {
-	beego.Controller
-}
-
-// @Title CreateUser
-// @Description create users
-// @Param	body		body 	models.User	true		"body for user content"
-// @Success 200 {int} models.User.Id
-// @Failure 403 body is empty
-// @router / [post]
-func (u *UserController) Post() {
-	var user models.User
-	json.Unmarshal(u.Ctx.Input.RequestBody, &user)
-	uid := models.AddUser(user)
-	u.Data["json"] = map[string]string{"uid": uid}
-	u.ServeJSON()
-}
-
-// @Title GetAll
-// @Description get all Users
-// @Success 200 {object} models.User
-// @router / [get]
-func (u *UserController) GetAll() {
-	users := models.GetAllUsers()
-	u.Data["json"] = users
-	u.ServeJSON()
-}
-
-// @Title Get
-// @Description get user by uid
-// @Param	uid		path 	string	true		"The key for staticblock"
-// @Success 200 {object} models.User
-// @Failure 403 :uid is empty
-// @router /:uid [get]
-func (u *UserController) Get() {
-	uid := u.GetString(":uid")
-	if uid != "" {
-		user, err := models.GetUser(uid)
-		if err != nil {
-			u.Data["json"] = err.Error()
-		} else {
-			u.Data["json"] = user
-		}
-	}
-	u.ServeJSON()
-}
-
-// @Title Update
-// @Description update the user
-// @Param	uid		path 	string	true		"The uid you want to update"
-// @Param	body		body 	models.User	true		"body for user content"
-// @Success 200 {object} models.User
-// @Failure 403 :uid is not int
-// @router /:uid [put]
-func (u *UserController) Put() {
-	uid := u.GetString(":uid")
-	if uid != "" {
-		var user models.User
-		json.Unmarshal(u.Ctx.Input.RequestBody, &user)
-		uu, err := models.UpdateUser(uid, &user)
-		if err != nil {
-			u.Data["json"] = err.Error()
-		} else {
-			u.Data["json"] = uu
-		}
-	}
-	u.ServeJSON()
-}
-
-// @Title Delete
-// @Description delete the user
-// @Param	uid		path 	string	true		"The uid you want to delete"
-// @Success 200 {string} delete success!
-// @Failure 403 uid is empty
-// @router /:uid [delete]
-func (u *UserController) Delete() {
-	uid := u.GetString(":uid")
-	models.DeleteUser(uid)
-	u.Data["json"] = "delete success!"
-	u.ServeJSON()
-}
-
-// @Title Login
-// @Description Logs user into the system
-// @Param	username		query 	string	true		"The username for login"
-// @Param	password		query 	string	true		"The password for login"
-// @Success 200 {string} login success
-// @Failure 403 user not exist
-// @router /login [get]
-func (u *UserController) Login() {
-	username := u.GetString("username")
-	password := u.GetString("password")
-	if models.Login(username, password) {
-		u.Data["json"] = "login success"
-	} else {
-		u.Data["json"] = "user not exist"
-	}
-	u.ServeJSON()
-}
-
-// @Title logout
-// @Description Logs out current logged in user session
-// @Success 200 {string} logout success
-// @router /logout [get]
-func (u *UserController) Logout() {
-	u.Data["json"] = "logout success"
-	u.ServeJSON()
-}
-

+ 6 - 4
go.mod

@@ -4,15 +4,18 @@ go 1.21
 
 require github.com/beego/beego/v2 v2.1.0
 
-require github.com/smartystreets/goconvey v1.6.4
+require (
+	github.com/beego/bee/v2 v2.1.0
+	github.com/go-redis/redis/v8 v8.11.5
+	github.com/rdlucklib/rdluck_tools v1.0.3
+)
 
 require (
 	github.com/beorn7/perks v1.0.1 // indirect
 	github.com/cespare/xxhash/v2 v2.2.0 // indirect
+	github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
 	github.com/golang/protobuf v1.5.3 // indirect
-	github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 // indirect
 	github.com/hashicorp/golang-lru v0.5.4 // indirect
-	github.com/jtolds/gls v4.20.0+incompatible // indirect
 	github.com/kr/text v0.2.0 // indirect
 	github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
 	github.com/mitchellh/mapstructure v1.5.0 // indirect
@@ -22,7 +25,6 @@ require (
 	github.com/prometheus/common v0.42.0 // indirect
 	github.com/prometheus/procfs v0.9.0 // indirect
 	github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 // indirect
-	github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect
 	golang.org/x/crypto v0.0.0-20220315160706-3147a52a75dd // indirect
 	golang.org/x/net v0.7.0 // indirect
 	golang.org/x/sys v0.6.0 // indirect

+ 39 - 0
models/base.go

@@ -0,0 +1,39 @@
+package models
+
+type BaseResponse struct {
+	Ret         int
+	Msg         string
+	ErrMsg      string
+	ErrCode     string
+	Data        interface{}
+	Success     bool `description:"true 执行成功,false 执行失败"`
+	IsSendEmail bool `json:"-" description:"true 发送邮件,false 不发送邮件"`
+	IsAddLog    bool `json:"-" description:"true 新增操作日志,false 不新增操作日志" `
+}
+
+type BaseResponseRef struct {
+	Ret     int
+	Msg     string
+	ErrMsg  string
+	ErrCode string
+	Data    string
+}
+
+type BaseResponseResult struct {
+	Ret     int    `description:"状态:200 成功,408 重新登录,403:为失败"`
+	Msg     string `description:"提示信息,对用户展示"`
+	ErrMsg  string `description:"错误信息,供开发定位问题"`
+	ErrCode string `description:"错误编码,预留"`
+	Data    string `description:"返回数据,json格式字符串"`
+}
+
+func (r *BaseResponse) Init() *BaseResponse {
+	return &BaseResponse{Ret: 403, IsSendEmail: true}
+}
+
+type BaseRequest struct {
+}
+
+func (br *BaseRequest) Init() *BaseRequest {
+	return &BaseRequest{}
+}

+ 22 - 0
models/classify.go

@@ -0,0 +1,22 @@
+package models
+
+import "time"
+
+type ClassifyDetail struct {
+	ClassifyId     int       `description:"分类id"`
+	ClassifyName   string    `description:"分类名称"`
+	Sort           int       `json:"-"`
+	ParentId       int       `description:"父级分类id"`
+	CreateTime     time.Time `description:"创建时间"`
+	ModifyTime     time.Time `description:"修改时间"`
+	Abstract       string    `description:"栏目简介"`
+	Descript       string    `description:"分享描述"`
+	ReportAuthor   string    `description:"栏目作者"`
+	AuthorDescript string    `description:"作者简介"`
+	ColumnImgUrl   string    `description:"栏目配图"`
+	HeadImgUrl     string    `description:"头部banner"`
+	AvatarImgUrl   string    `description:"头像"`
+	ReportImgUrl   string    `description:"报告配图"`
+	HomeImgUrl     string    `description:"首页配图"`
+	Stage          int       `description:"最新期数"`
+}

+ 70 - 0
models/report.go

@@ -0,0 +1,70 @@
+package models
+
+import (
+	"time"
+
+	"github.com/beego/beego/v2/client/orm"
+)
+
+type ReportList struct {
+	Id                 int       `description:"报告Id"`
+	AddType            int       `description:"新增方式:1:新增报告,2:继承报告"`
+	ClassifyIdFirst    int       `description:"一级分类id"`
+	ClassifyNameFirst  string    `description:"一级分类名称"`
+	ClassifyIdSecond   int       `description:"二级分类id"`
+	ClassifyNameSecond string    `description:"二级分类名称"`
+	Title              string    `description:"标题"`
+	Abstract           string    `description:"摘要"`
+	Author             string    `description:"作者"`
+	Frequency          string    `description:"频度"`
+	CreateTime         string    `description:"创建时间"`
+	ModifyTime         time.Time `description:"修改时间"`
+	State              int       `description:"1:未发布,2:已发布"`
+	PublishTime        string    `description:"发布时间"`
+	Stage              int       `description:"期数"`
+	MsgIsSend          int       `description:"消息是否已发送,0:否,1:是"`
+	Content            string    `description:"内容"`
+	VideoUrl           string    `description:"音频文件URL"`
+	VideoName          string    `description:"音频文件名称"`
+	VideoPlaySeconds   string    `description:"音频播放时长"`
+	VideoSize          string    `description:"音频文件大小,单位M"`
+	HasPermission      int       `description:"是否拥有报告权限,1:拥有,0:没有"`
+	TitleType          string    `description:"标题类型,FICC或者权益"`
+	IsCurrentDate      int       `description:"是否当前日期:1是,0不是"`
+	ClassifyDetail
+}
+
+func GetReportListCount(classifyId int) (count int, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := ` SELECT COUNT(*) AS count FROM report WHERE 1=1 AND state=2 AND classify_id_second=? `
+	err = o.Raw(sql, classifyId).QueryRow(&count)
+	return
+}
+
+func GetReportList(classifyId, startSize, pageSize int) (items []*ReportList, err error) {
+	o := orm.NewOrmUsingDB("rddp")
+	sql := ` SELECT a.id,a.add_type,a.classify_id_first,a.classify_name_first,a.classify_id_second,a.classify_name_second,a.title,a.abstract,a.author,a.frequency,
+			a.create_time,a.modify_time,a.state,a.publish_time,a.stage,a.msg_is_send,b.id AS classify_id,b.classify_name,b.descript,b.report_author,b.author_descript,
+            b.report_img_url,b.head_img_url,b.avatar_img_url,b.column_img_url,a.video_url,a.video_name,a.video_play_seconds,a.video_size,
+            CASE WHEN DATE(a.modify_time)=DATE(NOW()) THEN 1 ELSE 0 END AS is_current_date
+            FROM report AS a
+			INNER JOIN  classify AS b ON a.classify_id_second=b.id
+			WHERE a.state=2 AND a.classify_id_second=? ORDER BY  a.publish_time DESC LIMIT ?,? `
+	_, err = o.Raw(sql, classifyId, startSize, pageSize).QueryRows(&items)
+	return
+}
+
+func GetReportPermission(userId int, classifyNameSecond string) (count int, err error) {
+	o := orm.NewOrm()
+	sql := ` SELECT COUNT(1) AS count
+            FROM company_report_permission AS crp
+            INNER JOIN  chart_permission_chapter_mapping AS cpcm ON crp.chart_permission_id = cpcm.chart_permission_id
+            INNER JOIN chart_permission_search_key_word_mapping AS cskwm ON cskwm.chart_permission_id=crp.chart_permission_id
+            INNER JOIN wx_user wu ON wu.company_id = crp.company_id
+            WHERE wu.user_id = ?
+            AND cpcm.research_type = 'rddp'
+			AND cskwm.from='rddp'
+			AND cskwm.key_word=? `
+	err = o.Raw(sql, userId, classifyNameSecond).QueryRow(&count)
+	return
+}

+ 12 - 0
models/response/report.go

@@ -0,0 +1,12 @@
+package response
+
+import (
+	"eta/eta_mini_bridge/models"
+
+	"github.com/rdlucklib/rdluck_tools/paging"
+)
+
+type ReportListResp struct {
+	List   []*models.ReportList
+	Paging *paging.PagingItem
+}

+ 63 - 64
models/user.go

@@ -1,86 +1,85 @@
 package models
 
 import (
-	"errors"
-	"strconv"
 	"time"
-)
 
-var (
-	UserList map[string]*User
+	"github.com/beego/beego/v2/client/orm"
 )
 
-func init() {
-	UserList = make(map[string]*User)
-	u := User{"user_11111", "astaxie", "11111", Profile{"male", 20, "Singapore", "astaxie@gmail.com"}}
-	UserList["user_11111"] = &u
-}
-
 type User struct {
-	Id       string
-	Username string
-	Password string
-	Profile  Profile
+	UserId         int       `orm:"pk" description:"用户id"`
+	OpenId         string    `description:"openid"`
+	UnionId        string    `description:"unionid"`
+	RealName       string    `description:"姓名"`
+	Phone          string    `description:"手机号"`
+	AreaCode       string    `description:"区号"`
+	Email          string    `description:"邮箱"`
+	SellerId       int       `description:"销售id(SysUserId)"`
+	Company        string    `description:"所属公司"`
+	ValidStartTime time.Time `description:"有效期开始时间"`
+	ValidEndTime   time.Time `description:"有效期结束时间"`
+	Status         int       `description:"用户类型: 0表示禁用,1表示潜在客户,2表示正式客户"`
+	CreateTime     time.Time `description:"系统中首次新增用户的时间"`
+	ModifyTime     time.Time `description:"系统中用户信息变更的时间"`
+	RegisterTime   time.Time `description:"用户首次登录小程序的时间"`
+	IsSubscribed   bool      `description:"是否关注公众号: 0表示没有关注,1表示关注"`
+	IsRegistered   bool      `description:"是否注册: 0表示没有注册,1表示注册"`
 }
 
-type Profile struct {
-	Gender  string
-	Age     int
-	Address string
-	Email   string
+func (u *User) Insert() (insertId int64, err error) {
+	o := orm.NewOrmUsingDB("master")
+	insertId, err = o.Insert(u)
+	return
 }
 
-func AddUser(u User) string {
-	u.Id = "user_" + strconv.FormatInt(time.Now().UnixNano(), 10)
-	UserList[u.Id] = &u
-	return u.Id
+type UserItem struct {
+	UserId       int       `description:"用户id"`
+	OpenId       string    `description:"open_id"`
+	UnionId      string    `description:"union_id"`
+	NickName     string    `description:"用户昵称"`
+	RealName     string    `description:"用户实际名称"`
+	Phone        string    `description:"手机号码"`
+	Componey     string    `description:"所属公司"`
+	AreaCode     string    `description:"区号"`
+	SellerId     int       `description:"销售id"`
+	Email        string    `description:"邮箱"`
+	Headimgurl   string    `description:"用户头像,最后一个数值代表正方形头像大小(有0、46、64、96、132数值可选,0代表640*640正方形头像),用户没有头像时该项为空"`
+	ValidEndTime time.Time `description:"服务截至时间"`
+	RegisterTime time.Time `description:"登录时间,用户首次登录小程序的时间"`
+	CreateTime   time.Time `description:"系统中新增用户的时间"`
+	ModifyTime   time.Time `description:"系统中用户信息更新的时间"`
+	IsRegistered bool      `description:"是否注册:1:已注册,0:未注册"`
 }
 
-func GetUser(uid string) (u *User, err error) {
-	if u, ok := UserList[uid]; ok {
-		return u, nil
-	}
-	return nil, errors.New("User not exists")
+// 变更联系人是否已注册状态
+func ModifyUserRegisterStatus(userId int, status bool, registerTime, modifyTime time.Time) (err error) {
+	o := orm.NewOrmUsingDB("master")
+	sql := `UPDATE user SET is_registered=?, register_time=?, modify_time=? WHERE user_id = ? `
+	_, err = o.Raw(sql, status, registerTime, modifyTime, userId).Exec()
+	return
 }
 
-func GetAllUsers() map[string]*User {
-	return UserList
+func GetUserById(userId int) (item *User, err error) {
+	o := orm.NewOrmUsingDB("master")
+	sql := `SELECT * FROM user WHERE user_id=? `
+	err = o.Raw(sql, userId).QueryRow(&item)
+	return
 }
 
-func UpdateUser(uid string, uu *User) (a *User, err error) {
-	if u, ok := UserList[uid]; ok {
-		if uu.Username != "" {
-			u.Username = uu.Username
-		}
-		if uu.Password != "" {
-			u.Password = uu.Password
-		}
-		if uu.Profile.Age != 0 {
-			u.Profile.Age = uu.Profile.Age
-		}
-		if uu.Profile.Address != "" {
-			u.Profile.Address = uu.Profile.Address
-		}
-		if uu.Profile.Gender != "" {
-			u.Profile.Gender = uu.Profile.Gender
-		}
-		if uu.Profile.Email != "" {
-			u.Profile.Email = uu.Profile.Email
-		}
-		return u, nil
-	}
-	return nil, errors.New("User Not Exist")
+func GetUserItemByPhone(phone string) (item *UserItem, err error) {
+	o := orm.NewOrmUsingDB("master")
+	sql := `SELECT * FROM user WHERE phone=? `
+	err = o.Raw(sql, phone).QueryRow(&item)
+	return
 }
 
-func Login(username, password string) bool {
-	for _, u := range UserList {
-		if u.Username == username && u.Password == password {
-			return true
-		}
-	}
-	return false
+func GetUserItemByEmail(email string) (item *UserItem, err error) {
+	sql := `SELECT * FROM user WHERE email=? `
+	err = orm.NewOrm().Raw(sql, email).QueryRow(&item)
+	return
 }
-
-func DeleteUser(uid string) {
-	delete(UserList, uid)
+func GetUserItemByUserId(userId int) (item *UserItem, err error) {
+	sql := `SELECT * FROM user WHERE user_id=? `
+	err = orm.NewOrm().Raw(sql, userId).QueryRow(&item)
+	return
 }

+ 32 - 0
models/user_record.go

@@ -0,0 +1,32 @@
+package models
+
+import (
+	"time"
+
+	"github.com/beego/beego/v2/client/orm"
+)
+
+type UserRecord struct {
+	UserRecordId  int       `orm:"column(user_record_id);pk"`
+	OpenId        string    `description:"用户openid,最大长度:32"`
+	UnionId       string    `description:"用户unionid,最大长度:64"`
+	Subscribe     int       `description:"是否关注"`
+	SubscribeTime time.Time `description:""`
+	NickName      string    `descritpion:"用户昵称,最大长度:32"`
+	RealName      string    `descritpion:"用户实际名称,最大长度:32"`
+	Sex           int       `descritpion:"普通用户性别,1为男性,2为女性"`
+	Province      string    `description:"普通用户个人资料填写的省份,最大长度:30"`
+	City          string    `description:"普通用户个人资料填写的城市,最大长度:30"`
+	Country       string    `description:"国家,如中国为CN,最大长度:30"`
+	Headimgurl    string    `description:"用户第三方(微信)头像,最大长度:512"`
+	CreateTime    time.Time `description:"创建时间,关系添加时间、用户授权时间"`
+	SessionKey    string    `description:"微信小程序会话密钥,最大长度:255"`
+	UserId        int       `description:"用户id"`
+}
+
+// 根据用户id和平台id获取用户关系
+func GetUserRecordByUserId(userId int) (item *UserRecord, err error) {
+	sql := `SELECT * FROM user_record WHERE user_id=? `
+	err = orm.NewOrm().Raw(sql, userId).QueryRow(&item)
+	return
+}

+ 46 - 0
services/user.go

@@ -0,0 +1,46 @@
+package services
+
+import (
+	"eta/eta_mini_bridge/models"
+	"eta/eta_mini_bridge/utils"
+)
+
+// 根据用户id和平台id获取用户信息
+func GetUserItemByUserId(userId int) (UserItem *models.UserItem, err error) {
+	//获取用户信息
+	UserItem, wxUserErr := models.GetUserItemByUserId(userId)
+	if wxUserErr != nil {
+		err = wxUserErr
+		return
+	}
+	//格式化返回用户数据
+	formatWxUser(UserItem)
+	return
+}
+
+// 通过用户 用户记录  和  来源平台  格式化返回 用户数据
+func formatWxUser(wxUser *models.UserItem) {
+	//根据用户id和平台id获取用户关系
+	userRecord, userRecordErr := models.GetUserRecordByUserId(wxUser.UserId)
+	if userRecordErr != nil {
+		if userRecordErr.Error() != utils.ErrNoRow() {
+			return
+		}
+		if userRecordErr.Error() == utils.ErrNoRow() {
+			return
+		}
+	}
+
+	//该openid在系统中没有关联关系
+	if userRecord == nil {
+		return
+	}
+
+	wxUser.OpenId = userRecord.OpenId
+	wxUser.UnionId = userRecord.UnionId
+	wxUser.NickName = userRecord.NickName
+	//wxUser.RealName = userRecord.RealName
+	//wxUser.BindAccount = userRecord.BindAccount
+	wxUser.Headimgurl = userRecord.Headimgurl
+	return
+}

+ 32 - 0
services/user_permission.go

@@ -0,0 +1,32 @@
+package services
+
+import (
+	"errors"
+	"eta/eta_mini_bridge/utils"
+	"strconv"
+)
+
+func CheckUserPermission(userId int) (status int, err error) {
+	if userId > 0 {
+		user, err := GetUserItemByUserId(userId)
+		if err != nil {
+			status = 40001
+			if err.Error() == utils.ErrNoRow() {
+				err = errors.New("用户信息不存在:userId:" + strconv.Itoa(userId))
+				return status, err
+			}
+			err = errors.New("获取用户信息失败:userId:" + strconv.Itoa(userId) + ";Err:" + err.Error())
+			return status, err
+		}
+		if user == nil {
+			status = 40001
+			err = errors.New("获取用户信息失败:userId:" + strconv.Itoa(userId))
+			return status, err
+		}
+
+	} else {
+		status = 40001
+		err = errors.New("用户id错误")
+	}
+	return
+}

+ 73 - 0
utils/common.go

@@ -0,0 +1,73 @@
+package utils
+
+import (
+	"crypto/hmac"
+	"crypto/sha256"
+	"encoding/base64"
+	"fmt"
+	"sort"
+	"strconv"
+	"strings"
+)
+
+// HmacSha256 计算HmacSha256
+// key 是加密所使用的key
+// data 是加密的内容
+func HmacSha256(key string, data string) []byte {
+	mac := hmac.New(sha256.New, []byte(key))
+	_, _ = mac.Write([]byte(data))
+
+	return mac.Sum(nil)
+}
+
+// 数据没有记录
+func ErrNoRow() string {
+	return "<QuerySeter> no row found"
+}
+
+// HmacSha256ToBase64 将加密后的二进制转Base64字符串
+func HmacSha256ToBase64(key string, data string) string {
+	return base64.URLEncoding.EncodeToString(HmacSha256(key, data))
+}
+
+func GetSign(nonce, timestamp, appId, secret string) (sign string) {
+	signStrMap := map[string]string{
+		"nonce":     nonce,
+		"timestamp": timestamp,
+		"appid":     appId,
+	}
+	keys := make([]string, 0, len(signStrMap))
+	for k := range signStrMap {
+		keys = append(keys, k)
+	}
+	sort.Strings(keys)
+	var signStr string
+	for _, k := range keys {
+		signStr += k + "=" + signStrMap[k] + "&"
+	}
+	signStr = strings.Trim(signStr, "&")
+	fmt.Println("signStr:" + signStr)
+	sign = HmacSha256ToBase64(secret, signStr)
+	return
+}
+
+func StringsToJSON(str string) string {
+	rs := []rune(str)
+	jsons := ""
+	for _, r := range rs {
+		rint := int(r)
+		if rint < 128 {
+			jsons += string(r)
+		} else {
+			jsons += "\\u" + strconv.FormatInt(int64(rint), 16) // json
+		}
+	}
+	return jsons
+}
+
+func StartIndex(page, pagesize int) int {
+	if page > 1 {
+		return (page - 1) * pagesize
+	}
+	return 0
+}

+ 70 - 0
utils/config.go

@@ -0,0 +1,70 @@
+package utils
+
+import (
+	"fmt"
+
+	beeLogger "github.com/beego/bee/v2/logger"
+	"github.com/beego/beego/v2/server/web"
+)
+
+// 数据库配置
+var (
+	RunMode          string // 运行模式
+	MYSQL_URL_MASTER string // 数据库地址
+	MYSQL_URL_RDDP   string // 数据库地址
+
+	REDIS_CACHE string      //缓存地址
+	Rc          RedisClient //redis缓存
+)
+
+var (
+	LogPath    string //调用过程中的日志存放地址
+	LogFile    string
+	ApiLogPath string // 接口请求地址和接口返回值日志存放地址
+	ApiLogFile string
+	BinLogPath string // 数据库相关的日志存放地址
+	BinLogFile string
+	LogMaxDays int // 日志最大保留天数
+)
+
+// 小程序服务通信密钥
+var (
+	ETA_MINI_API_APPID  string
+	ETA_MINI_API_SECRET string
+)
+
+func init() {
+	tmpRunMode, err := web.AppConfig.String("run_mode")
+	if err != nil {
+		panic(any("配置文件读取run_mode错误 " + err.Error()))
+	}
+	RunMode = tmpRunMode
+	fmt.Println("RunMode:", RunMode)
+
+	config, err := web.AppConfig.GetSection(RunMode)
+	if err != nil {
+		panic(any("配置文件读取错误 " + err.Error()))
+	}
+	beeLogger.Log.Info(RunMode + " 模式")
+
+	ETA_MINI_API_APPID = config["eta_mini_api_appid"]
+	ETA_MINI_API_SECRET = config["eta_mini_api_secret"]
+	// 数据库配置
+	MYSQL_URL_RDDP = config["mysql_url_rddp"]
+	MYSQL_URL_MASTER = config["mysql_url_master"]
+
+	// redis缓存配置
+	REDIS_CACHE = config["beego_cache"]
+	if len(REDIS_CACHE) <= 0 {
+		panic(any("redis链接参数没有配置"))
+	}
+	// 初始化缓存
+	redisClient, err := initRedis(config["redis_type"], config["beego_cache"])
+	if err != nil {
+		fmt.Println("redis链接异常:", err)
+		panic(any("redis链接参数没有配置"))
+	}
+
+	Rc = redisClient
+
+}

+ 15 - 0
utils/constants.go

@@ -0,0 +1,15 @@
+package utils
+
+// 常量定义
+const (
+	FormatTime            = "15:04:05"                //时间格式
+	FormatDate            = "2006-01-02"              //日期格式
+	FormatDateTime        = "2006-01-02 15:04:05"     //完整时间格式
+	HlbFormatDateTime     = "2006-01-02_15:04:05.999" //完整时间格式
+	FormatDateTimeUnSpace = "20060102150405"          //完整时间格式
+	PageSize15            = 15                        //列表页每页数据量
+	PageSize5             = 5
+	PageSize10            = 10
+	PageSize20            = 20
+	PageSize30            = 30
+)

+ 114 - 0
utils/logs.go

@@ -0,0 +1,114 @@
+package utils
+
+import (
+	"encoding/json"
+	"os"
+	"path"
+
+	"github.com/beego/beego/v2/core/logs"
+)
+
+const (
+	DefaultLogPath    = "./etalogs/filelog"
+	DefaultBinlogPath = "./etalogs/binlog"
+	DefaultApiLogPath = "./etalogs/apilog"
+)
+
+var (
+	BinLog  *logs.BeeLogger
+	ApiLog  *logs.BeeLogger
+	FileLog *logs.BeeLogger
+)
+
+func init() {
+	if LogMaxDays == 0 {
+		LogMaxDays = 30
+	}
+	logPath := LogPath
+	if logPath == "" {
+		logPath = DefaultLogPath
+	}
+	logFile := LogFile
+	if logFile == "" {
+		logFile = "filelog.log"
+	}
+	os.MkdirAll(logPath, os.ModePerm)
+
+	// 打开文件
+	logFileName := path.Join(logPath, logFile)
+	FileLog = logs.NewLogger(1000000)
+	logConf := getDefaultLogConfig()
+
+	logConf.FileName = logFileName
+	b, _ := json.Marshal(logConf)
+	FileLog.SetLogger(logs.AdapterFile, string(b))
+	FileLog.EnableFuncCallDepth(true)
+	initApiLog()
+	initBinLog()
+}
+
+// 初始化apilog日志
+func initApiLog() {
+	apilogPath := ApiLogPath
+	if apilogPath == "" {
+		apilogPath = DefaultApiLogPath
+	}
+	apilogFile := ApiLogFile
+	if apilogFile == "" {
+		apilogFile = "apilog.log"
+	}
+	os.MkdirAll(apilogPath, os.ModePerm)
+	logFileName := path.Join(apilogPath, apilogFile)
+	ApiLog = logs.NewLogger(1000000)
+	logConf := getDefaultLogConfig()
+	logConf.FileName = logFileName
+
+	b, _ := json.Marshal(logConf)
+	ApiLog.SetLogger(logs.AdapterFile, string(b))
+	ApiLog.EnableFuncCallDepth(true)
+}
+
+// 初始化binlog日志
+func initBinLog() {
+	binlogPath := BinLogPath
+	if binlogPath == "" {
+		binlogPath = DefaultBinlogPath
+	}
+	binlogFile := BinLogFile
+	if binlogFile == "" {
+		binlogFile = "binlog.log"
+	}
+	os.MkdirAll(binlogPath, os.ModePerm)
+	logFileName := path.Join(binlogPath, binlogFile)
+	BinLog = logs.NewLogger(1000000)
+	logConf := getDefaultLogConfig()
+	logConf.FileName = logFileName
+
+	b, _ := json.Marshal(logConf)
+	BinLog.SetLogger(logs.AdapterFile, string(b))
+	BinLog.EnableFuncCallDepth(true)
+}
+
+type logConfig struct {
+	FileName string `json:"filename" description:"保存的文件名"`
+	MaxLines int    `json:"maxlines"  description:"每个文件保存的最大行数,默认值 1000000"`
+	MaxSize  int    `json:"maxsize" description:"每个文件保存的最大尺寸,默认值是 1 << 28, //256 MB"`
+	Daily    bool   `json:"daily" description:"是否按照每天 logrotate,默认是 true"`
+	MaxDays  int    `json:"maxdays" description:"文件最多保存多少天,默认保存 7 天"`
+	Rotate   bool   `json:"rotate" description:"是否开启 logrotate,默认是 true"`
+	Level    int    `json:"level" description:"日志保存的时候的级别,默认是 Trace 级别"`
+	Color    bool   `json:"color" description:"日志是否输出颜色"`
+}
+
+func getDefaultLogConfig() logConfig {
+	return logConfig{
+		FileName: "",
+		MaxLines: 10000000,
+		MaxSize:  1 << 28,
+		Daily:    true,
+		MaxDays:  LogMaxDays,
+		Rotate:   true,
+		Level:    logs.LevelTrace,
+		//Perm:     "",
+	}
+}

+ 33 - 0
utils/redis.go

@@ -0,0 +1,33 @@
+package utils
+
+import (
+	"eta/eta_mini_bridge/utils/redis"
+	"time"
+)
+
+type RedisClient interface {
+	Get(key string) interface{}
+	RedisBytes(key string) (data []byte, err error)
+	RedisString(key string) (data string, err error)
+	RedisInt(key string) (data int, err error)
+	Put(key string, val interface{}, timeout time.Duration) error
+	SetNX(key string, val interface{}, timeout time.Duration) bool
+	Delete(key string) error
+	IsExist(key string) bool
+	LPush(key string, val interface{}) error
+	Brpop(key string, callback func([]byte))
+	GetRedisTTL(key string) time.Duration
+	Incrby(key string, num int) (interface{}, error)
+	Do(commandName string, args ...interface{}) (reply interface{}, err error)
+}
+
+func initRedis(redisType string, conf string) (redisClient RedisClient, err error) {
+	switch redisType {
+	case "cluster": // 集群
+		redisClient, err = redis.InitClusterRedis(conf)
+	default: // 默认走单机
+		redisClient, err = redis.InitStandaloneRedis(conf)
+	}
+
+	return
+}

+ 263 - 0
utils/redis/cluster_redis.go

@@ -0,0 +1,263 @@
+package redis
+
+import (
+	"context"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"strings"
+	"time"
+
+	"github.com/go-redis/redis/v8"
+)
+
+// ClusterRedisClient
+// @Description: 集群的redis客户端
+type ClusterRedisClient struct {
+	redisClient *redis.ClusterClient
+}
+
+var DefaultKey = "zcmRedis"
+
+// InitClusterRedis
+// @Description: 初始化集群redis客户端
+// @param config
+// @return clusterRedisClient
+// @return err
+func InitClusterRedis(config string) (clusterRedisClient *ClusterRedisClient, err error) {
+	var cf map[string]string
+	err = json.Unmarshal([]byte(config), &cf)
+	if err != nil {
+		return
+	}
+
+	// 集群地址
+	connList := make([]string, 0)
+	if _, ok := cf["conn"]; !ok {
+		err = errors.New("config has no conn key")
+		return
+	} else {
+		connList = strings.Split(cf["conn"], ",")
+		if len(connList) <= 1 {
+			err = errors.New("conn address less than or equal to 1")
+			return
+		}
+	}
+
+	// 密码
+	if _, ok := cf["password"]; !ok {
+		cf["password"] = ""
+	}
+
+	// 创建 Redis 客户端配置对象
+	clusterOptions := &redis.ClusterOptions{
+		Addrs:    connList, // 设置 Redis 节点的 IP 地址和端口号
+		Password: cf["password"],
+	}
+
+	// 创建 Redis 集群客户端
+	client := redis.NewClusterClient(clusterOptions)
+
+	// 测试连接并获取信息
+	_, err = client.Ping(context.TODO()).Result()
+	if err != nil {
+		err = errors.New("redis 链接失败:" + err.Error())
+		return
+	}
+
+	clusterRedisClient = &ClusterRedisClient{redisClient: client}
+
+	return
+}
+
+// Get
+// @Description: 根据key获取数据(其实是返回的字节编码)
+// @receiver rc
+// @param key
+// @return interface{}
+func (rc *ClusterRedisClient) Get(key string) interface{} {
+	data, err := rc.redisClient.Get(context.TODO(), key).Bytes()
+	if err != nil {
+		return nil
+	}
+
+	return data
+}
+
+// RedisBytes
+// @Description: 根据key获取字节编码数据
+// @receiver rc
+// @param key
+// @return data
+// @return err
+func (rc *ClusterRedisClient) RedisBytes(key string) (data []byte, err error) {
+	data, err = rc.redisClient.Get(context.TODO(), key).Bytes()
+
+	return
+}
+
+// RedisString
+// @Description: 根据key获取字符串数据
+// @receiver rc
+// @param key
+// @return data
+// @return err
+func (rc *ClusterRedisClient) RedisString(key string) (data string, err error) {
+	data, err = rc.redisClient.Get(context.TODO(), key).Result()
+
+	return
+}
+
+// RedisInt
+// @Description: 根据key获取int数据
+// @receiver rc
+// @param key
+// @return data
+// @return err
+func (rc *ClusterRedisClient) RedisInt(key string) (data int, err error) {
+	data, err = rc.redisClient.Get(context.TODO(), key).Int()
+
+	return
+}
+
+// Put
+// @Description: put一个数据到redis
+// @receiver rc
+// @param key
+// @param val
+// @param timeout
+// @return error
+func (rc *ClusterRedisClient) Put(key string, val interface{}, timeout time.Duration) error {
+	var err error
+	err = rc.redisClient.SetEX(context.TODO(), key, val, timeout).Err()
+	if err != nil {
+		return err
+	}
+
+	err = rc.redisClient.HSet(context.TODO(), DefaultKey, key, true).Err()
+
+	return err
+}
+
+// SetNX
+// @Description: 设置一个会过期时间的值
+// @receiver rc
+// @param key
+// @param val
+// @param timeout
+// @return bool
+func (rc *ClusterRedisClient) SetNX(key string, val interface{}, timeout time.Duration) bool {
+	result, err := rc.redisClient.SetNX(context.TODO(), key, val, timeout).Result()
+	if err != nil {
+		return false
+	}
+
+	return result
+}
+
+// Delete
+// @Description: 删除redis中的键值对
+// @receiver rc
+// @param key
+// @return error
+func (rc *ClusterRedisClient) Delete(key string) error {
+	var err error
+
+	err = rc.redisClient.Del(context.TODO(), key).Err()
+	if err != nil {
+		return err
+	}
+
+	err = rc.redisClient.HDel(context.TODO(), DefaultKey, key).Err()
+
+	return err
+}
+
+// IsExist
+// @Description: 根据key判断是否写入缓存中
+// @receiver rc
+// @param key
+// @return bool
+func (rc *ClusterRedisClient) IsExist(key string) bool {
+	result, err := rc.redisClient.Exists(context.TODO(), key).Result()
+	if err != nil {
+		return false
+	}
+	if result == 0 {
+		_ = rc.redisClient.HDel(context.TODO(), DefaultKey, key).Err()
+		return false
+	}
+
+	return true
+}
+
+// LPush
+// @Description: 写入list
+// @receiver rc
+// @param key
+// @param val
+// @return error
+func (rc *ClusterRedisClient) LPush(key string, val interface{}) error {
+	data, _ := json.Marshal(val)
+	err := rc.redisClient.LPush(context.TODO(), key, data).Err()
+
+	return err
+}
+
+// Brpop
+// @Description: 从list中读取
+// @receiver rc
+// @param key
+// @param callback
+func (rc *ClusterRedisClient) Brpop(key string, callback func([]byte)) {
+	values, err := rc.redisClient.BRPop(context.TODO(), 1*time.Second, key).Result()
+	if err != nil {
+		return
+	}
+	if len(values) < 2 {
+		fmt.Println("assert is wrong")
+		return
+	}
+
+	callback([]byte(values[1]))
+
+}
+
+// GetRedisTTL
+// @Description: 获取key的过期时间
+// @receiver rc
+// @param key
+// @return time.Duration
+func (rc *ClusterRedisClient) GetRedisTTL(key string) time.Duration {
+	value, err := rc.redisClient.TTL(context.TODO(), key).Result()
+	if err != nil {
+		return 0
+	}
+
+	return value
+
+}
+
+// Incrby
+// @Description: 设置自增值
+// @receiver rc
+// @param key
+// @param num
+// @return interface{}
+// @return error
+func (rc *ClusterRedisClient) Incrby(key string, num int) (interface{}, error) {
+	return rc.redisClient.IncrBy(context.TODO(), key, int64(num)).Result()
+}
+
+// Do
+// @Description: cmd执行redis命令
+// @receiver rc
+// @param commandName
+// @param args
+// @return reply
+// @return err
+func (rc *ClusterRedisClient) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
+	newArgs := []interface{}{commandName}
+	newArgs = append(newArgs, args...)
+	return rc.redisClient.Do(context.TODO(), newArgs...).Result()
+}

+ 257 - 0
utils/redis/standalone_redis.go

@@ -0,0 +1,257 @@
+package redis
+
+import (
+	"context"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"github.com/go-redis/redis/v8"
+	"strconv"
+	"time"
+)
+
+// StandaloneRedisClient
+// @Description: 单机redis客户端
+type StandaloneRedisClient struct {
+	redisClient *redis.Client
+}
+
+func InitStandaloneRedis(config string) (standaloneRedis *StandaloneRedisClient, err error) {
+	var cf map[string]string
+	err = json.Unmarshal([]byte(config), &cf)
+	if err != nil {
+		return
+	}
+	//if _, ok := cf["key"]; !ok {
+	//	cf["key"] = DefaultKey
+	//}
+
+	if _, ok := cf["conn"]; !ok {
+		err = errors.New("config has no conn key")
+		return
+	}
+
+	// db库
+	dbNum := 0
+	// 如果指定了db库
+	if _, ok := cf["dbNum"]; ok {
+		dbNum, err = strconv.Atoi(cf["dbNum"])
+		if err != nil {
+			return
+		}
+	}
+
+	// 密码
+	if _, ok := cf["password"]; !ok {
+		cf["password"] = ""
+	}
+
+	client := redis.NewClient(&redis.Options{
+		Addr:     cf["conn"],
+		Password: cf["password"],
+		DB:       dbNum,
+		//PoolSize: 10, //连接池最大socket连接数,默认为10倍CPU数, 10 * runtime.NumCPU(暂不配置)
+	})
+
+	_, err = client.Ping(context.TODO()).Result()
+	if err != nil {
+		err = errors.New("redis 链接失败:" + err.Error())
+		return
+	}
+
+	standaloneRedis = &StandaloneRedisClient{redisClient: client}
+
+	return
+}
+
+// Get
+// @Description: 根据key获取数据(其实是返回的字节编码)
+// @receiver rc
+// @param key
+// @return interface{}
+func (rc *StandaloneRedisClient) Get(key string) interface{} {
+	data, err := rc.redisClient.Get(context.TODO(), key).Bytes()
+	if err != nil {
+		return nil
+	}
+
+	return data
+}
+
+// RedisBytes
+// @Description: 根据key获取字节编码数据
+// @receiver rc
+// @param key
+// @return data
+// @return err
+func (rc *StandaloneRedisClient) RedisBytes(key string) (data []byte, err error) {
+	data, err = rc.redisClient.Get(context.TODO(), key).Bytes()
+
+	return
+}
+
+// RedisString
+// @Description: 根据key获取字符串数据
+// @receiver rc
+// @param key
+// @return data
+// @return err
+func (rc *StandaloneRedisClient) RedisString(key string) (data string, err error) {
+	data, err = rc.redisClient.Get(context.TODO(), key).Result()
+
+	return
+}
+
+// RedisInt
+// @Description: 根据key获取int数据
+// @receiver rc
+// @param key
+// @return data
+// @return err
+func (rc *StandaloneRedisClient) RedisInt(key string) (data int, err error) {
+	data, err = rc.redisClient.Get(context.TODO(), key).Int()
+
+	return
+}
+
+// Put
+// @Description: put一个数据到redis
+// @receiver rc
+// @param key
+// @param val
+// @param timeout
+// @return error
+func (rc *StandaloneRedisClient) Put(key string, val interface{}, timeout time.Duration) error {
+	var err error
+	err = rc.redisClient.SetEX(context.TODO(), key, val, timeout).Err()
+	if err != nil {
+		return err
+	}
+
+	err = rc.redisClient.HSet(context.TODO(), DefaultKey, key, true).Err()
+
+	return err
+}
+
+// SetNX
+// @Description: 设置一个会过期时间的值
+// @receiver rc
+// @param key
+// @param val
+// @param timeout
+// @return bool
+func (rc *StandaloneRedisClient) SetNX(key string, val interface{}, timeout time.Duration) bool {
+	result, err := rc.redisClient.SetNX(context.TODO(), key, val, timeout).Result()
+	if err != nil {
+		return false
+	}
+
+	return result
+}
+
+// Delete
+// @Description: 删除redis中的键值对
+// @receiver rc
+// @param key
+// @return error
+func (rc *StandaloneRedisClient) Delete(key string) error {
+	var err error
+
+	err = rc.redisClient.Del(context.TODO(), key).Err()
+	if err != nil {
+		return err
+	}
+
+	err = rc.redisClient.HDel(context.TODO(), DefaultKey, key).Err()
+
+	return err
+}
+
+// IsExist
+// @Description: 根据key判断是否写入缓存中
+// @receiver rc
+// @param key
+// @return bool
+func (rc *StandaloneRedisClient) IsExist(key string) bool {
+	result, err := rc.redisClient.Exists(context.TODO(), key).Result()
+	if err != nil {
+		return false
+	}
+	if result == 0 {
+		_ = rc.redisClient.HDel(context.TODO(), DefaultKey, key).Err()
+		return false
+	}
+
+	return true
+}
+
+// LPush
+// @Description: 写入list
+// @receiver rc
+// @param key
+// @param val
+// @return error
+func (rc *StandaloneRedisClient) LPush(key string, val interface{}) error {
+	data, _ := json.Marshal(val)
+	err := rc.redisClient.LPush(context.TODO(), key, data).Err()
+
+	return err
+}
+
+// Brpop
+// @Description: 从list中读取
+// @receiver rc
+// @param key
+// @param callback
+func (rc *StandaloneRedisClient) Brpop(key string, callback func([]byte)) {
+	values, err := rc.redisClient.BRPop(context.TODO(), 1*time.Second, key).Result()
+	if err != nil {
+		return
+	}
+	if len(values) < 2 {
+		fmt.Println("assert is wrong")
+		return
+	}
+
+	callback([]byte(values[1]))
+
+}
+
+// GetRedisTTL
+// @Description: 获取key的过期时间
+// @receiver rc
+// @param key
+// @return time.Duration
+func (rc *StandaloneRedisClient) GetRedisTTL(key string) time.Duration {
+	value, err := rc.redisClient.TTL(context.TODO(), key).Result()
+	if err != nil {
+		return 0
+	}
+
+	return value
+
+}
+
+// Incrby
+// @Description: 设置自增值
+// @receiver rc
+// @param key
+// @param num
+// @return interface{}
+// @return error
+func (rc *StandaloneRedisClient) Incrby(key string, num int) (interface{}, error) {
+	return rc.redisClient.IncrBy(context.TODO(), key, int64(num)).Result()
+}
+
+// Do
+// @Description: cmd执行redis命令
+// @receiver rc
+// @param commandName
+// @param args
+// @return reply
+// @return err
+func (rc *StandaloneRedisClient) Do(commandName string, args ...interface{}) (reply interface{}, err error) {
+	newArgs := []interface{}{commandName}
+	newArgs = append(newArgs, args...)
+	return rc.redisClient.Do(context.TODO(), newArgs...).Result()
+}