Commit ad253400 by zhangjiec

1

parent 4caf690d
package api_admin
import (
"dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/data_db_cache/model"
"github.com/gin-gonic/gin"
"net/http"
)
// CreateArea 创建一个学校
// @Tags 管理后台
// @Summary 创建一个学校
// @Description 目前仅用于填充数据,暂未做权限校验
// @Accept json
// @Produce json
// @Param data body dbcurd.TableBaseArea true "学校信息"
// @Success 0 {object} integer
// @Router /ad/area [POST]
// @Security ApiKeyAuth
func CreateArea(c *gin.Context) {
var reqData dbcurd.TableBaseArea
err := c.ShouldBindJSON(&reqData)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqParaFormat,
"message": api.CodeMsg[api.ErrorReqParaFormat],
})
return
}
if reqData.CountyID == 0 || reqData.CountyID < 543 || reqData.CountyID > 3423 { // todoN 这里最好改成动态调整的
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqPara,
"message": api.CodeMsg[api.ErrorReqPara] + " county_id不正确",
})
return
}
insertRes := dbcurd.InsertBaseArea(&reqData) //插入数据库
if insertRes == 1 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorReqInsertDuplicate,
"data": api.CodeMsg[api.ErrorReqInsertDuplicate] + "(名字不可重复)",
})
return
} else if insertRes == 9 || reqData.ID == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"data": api.CodeMsg[api.ErrorSystemErr],
})
return
}
areaList := cache.GetCountyAreaMap(reqData.CountyID)
areaList = append(areaList, reqData.ID)
cache.CountyAreaMap.Store(reqData.CountyID, areaList) // 更新CountyAreaMap
cache.AreaMap.Store(reqData.ID, model.CacheBAreaStruct{ // AreaMap缓存,添加该校区
Name: reqData.Name,
Longitude: reqData.Longitude,
Latitude: reqData.Latitude,
CountyID: reqData.CountyID,
Status: reqData.Status,
})
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": reqData.ID,
})
}
//// CreateArea 创建一个学校
//// @Tags 管理后台
//// @Summary 创建一个学校
//// @Description 目前仅用于填充数据,暂未做权限校验
//// @Accept json
//// @Produce json
//// @Param data body dbcurd.TableBaseArea true "学校信息"
//// @Success 0 {object} integer
//// @Router /ad/area [POST]
//// @Security ApiKeyAuth
//func CreateArea(c *gin.Context) {
// var reqData dbcurd.TableBaseArea
// err := c.ShouldBindJSON(&reqData)
// if err != nil {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorReqParaFormat,
// "message": api.CodeMsg[api.ErrorReqParaFormat],
// })
// return
// }
// if reqData.CountyID == 0 || reqData.CountyID < 543 || reqData.CountyID > 3423 { // todoN 这里最好改成动态调整的
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorReqPara,
// "message": api.CodeMsg[api.ErrorReqPara] + " county_id不正确",
// })
// return
// }
//
// insertRes := dbcurd.InsertBaseArea(&reqData) //插入数据库
// if insertRes == 1 {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorReqInsertDuplicate,
// "data": api.CodeMsg[api.ErrorReqInsertDuplicate] + "(名字不可重复)",
// })
// return
// } else if insertRes == 9 || reqData.ID == 0 {
// c.JSON(http.StatusOK, gin.H{
// "code": api.ErrorSystemErr,
// "data": api.CodeMsg[api.ErrorSystemErr],
// })
// return
// }
//
// areaList := cache.GetCountyAreaMap(reqData.CountyID)
// areaList = append(areaList, reqData.ID)
// cache.CountyAreaMap.Store(reqData.CountyID, areaList) // 更新CountyAreaMap
// cache.AreaMap.Store(reqData.ID, model.CacheBAreaStruct{ // AreaMap缓存,添加该校区
// Name: reqData.Name,
// Longitude: reqData.Longitude,
// Latitude: reqData.Latitude,
// // CountyID: reqData.CountyID,
// Status: reqData.Status,
// })
//
// c.JSON(http.StatusOK, gin.H{
// "code": api.Success,
// "data": reqData.ID,
// })
//}
......@@ -6,6 +6,7 @@ import (
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger"
"dc_golang_server_1/thirdapi/chinamobile"
"fmt"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
......@@ -15,7 +16,7 @@ import (
// AddFamilyNum 添加亲情号
// @Tags 家长微信
// @Summary 添加亲情号 [complete]
// @Summary 添加亲情号(仅主家长有权限) [complete] 最新调整为仅主家长有权限
// @Description 家长绑定亲情号接口
// @Accept json
// @Produce json
......@@ -65,14 +66,14 @@ func AddFamilyNum(c *gin.Context) {
}
// 校验weUserID是否有cardUserID权限
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID)
if r < 2 {
if r != 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
})
return
}
if cardUserInfo.SimCardID == "" { // 学生未绑卡
if len(cardUserInfo.SimCardID) == 0 { // 学生未绑卡
c.JSON(
http.StatusOK,
gin.H{
......@@ -113,7 +114,14 @@ func AddFamilyNum(c *gin.Context) {
}
}
// 找移动添加亲情号 todo
// 找移动添加亲情号
if err = chinamobile.AddMemberVoiceWhiteList(cardUserInfo.SimCardID, reqData.Phone); err != nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": err.Error(),
})
return
}
// 写库
if dbcurd.InsertUSimFamilyNum(cardUserInfo.SimCardID, reqData.Phone, reqData.Nickname) == dbcurd.InsertSysErr {
......
......@@ -18,7 +18,7 @@ type apiDeleteFamilyNumStruct struct {
// DeleteFamilyNum 删除亲情号
// @Tags 家长微信
// @Summary 删除亲情号 [complete]
// @Summary 删除亲情号(仅主家长有权限) [complete] 最新调整为仅主家长有权限
// @Description 删除亲情号接口
// @Accept json
// @Produce json
......@@ -51,7 +51,7 @@ func DeleteFamilyNum(c *gin.Context) {
}
// 校验weUserID是否有cardUserID权限
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID)
if r < 2 {
if r != 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
......@@ -98,9 +98,6 @@ func DeleteFamilyNum(c *gin.Context) {
for i, family := range simInfoP.FamilyNum {
if family.Phone == reqData.Phone {
// 找移动删除亲情号 todo
// 考虑这下面的操作用事务处理成功了,再去找移动删,但是这样就要单独整个任务专门找移动搞,通过channel丢过去
// 本月删除亲情号次数加1
newCount := dbcurd.UpdateUSimInfoAddFamilyDeleteCount(cardUserInfo.SimCardID)
if newCount != simInfoP.FamilyDeleteCount-1 {
......@@ -111,7 +108,7 @@ func DeleteFamilyNum(c *gin.Context) {
}
simInfoP.FamilyDeleteCount = newCount
// 删库
if dbcurd.DeleteUSimFamilyNum(cardUserInfo.SimCardID, reqData.Phone) == false {
if dbcurd.UpdateUSimFamilyNumDeleteAt(cardUserInfo.SimCardID, reqData.Phone) == false {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"message": api.CodeMsg[api.ErrorSystemBusy] + "更新删除失败",
......
......@@ -11,8 +11,8 @@ import (
"strconv"
)
type GetCardUserAndTrendRes struct {
WeResUserInfoStruct
type getCardUserAndTrendRes struct {
weResUserInfoStruct
Service [6]uint8 `json:"service" example:"1,2,2,0,0,0"` // 对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)
Trend []model.CacheCardUserTrendStruct `json:"trend"`
}
......@@ -23,7 +23,7 @@ type GetCardUserAndTrendRes struct {
// @Description 传学生的ID,后台返回学生信息和最新动态
// @Produce json
// @Param id path integer true "学生ID"
// @Success 0 {object} GetCardUserAndTrendRes "学生信息和最新动态"
// @Success 0 {object} getCardUserAndTrendRes "学生信息和最新动态"
// @Router /we/cardusertrend/{id} [GET]
// @Security ApiKeyAuth
func GetCardUserAndTrend(c *gin.Context) {
......@@ -49,32 +49,32 @@ func GetCardUserAndTrend(c *gin.Context) {
return
}
// 查出该学生信息
cardUserInfo := cache.GetCardUserInfo(cardUserID)
if cardUserInfo == nil {
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID.(uint32))
if r < 2 { // 用户根本没得这个学生的权限,有问题
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
})
return
}
if cardUserInfo.MasterWechatUserID != weUserID { // 用户根本没得这个学生的权限,有问题
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
var master bool
if r == 2 {
master = true
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": GetCardUserAndTrendRes{
WeResUserInfoStruct: WeResUserInfoStruct{
ID: cardUserID,
Name: cardUserInfo.Name,
Sex: cardUserInfo.Sex,
Grade: cardUserInfo.Grade,
Class: cardUserInfo.Class,
StuNum: cardUserInfo.StuNum,
"data": getCardUserAndTrendRes{
weResUserInfoStruct: weResUserInfoStruct{
master,
cardUserID,
cardUserInfo.Name,
cardUserInfo.Sex,
cache.GetAreaMapName(cardUserInfo.AreaID, true),
cardUserInfo.Grade,
cardUserInfo.Class,
cardUserInfo.StuNum,
},
Service: [6]uint8{1, 2, 2, 2, 2, 2},
Trend: cache.GetCardUserTrendMapByCardUserID(cardUserID),
......
......@@ -11,7 +11,7 @@ import (
)
type GetCardUserInfoRes struct {
WeResUserInfoStruct
weResUserInfoStruct
Service [6]uint8 `json:"service" example:"1,2,2,0,0,0"` // 对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)
}
......@@ -46,27 +46,27 @@ func GetCardUser(c *gin.Context) {
})
return
}
// 查出该学生信息
cardUserInfo := cache.GetCardUserInfo(cardUserID)
if cardUserInfo == nil {
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID.(uint32))
if r < 2 { // 用户根本没得这个学生的权限,有问题
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
})
return
}
if cardUserInfo.MasterWechatUserID != weUserID { // 用户根本没得这个学生的权限,有问题
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"message": api.CodeMsg[api.ErrorUserRole],
})
return
var master bool
if r == 2 {
master = true
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": GetCardUserInfoRes{
WeResUserInfoStruct: WeResUserInfoStruct{
weResUserInfoStruct: weResUserInfoStruct{
master,
cardUserID,
cardUserInfo.Name,
cardUserInfo.Sex,
......
......@@ -9,8 +9,9 @@ import (
"net/http"
)
type WeResUserInfoStruct struct {
ID uint32 `json:"id"` // 学生ID
type weResUserInfoStruct struct {
Master bool `json:"master"` // 是否为主家长
ID uint32 `json:"id"` // 学生ID
Name string `json:"name"`
Sex uint8 `json:"sex"` // 0无意义 1女 2男
Area string `json:"area" example:"温江实验中学"` // 区域名字
......@@ -21,17 +22,17 @@ type WeResUserInfoStruct struct {
// TopUp bool `json:"topUp"` // 是否已充值(已充值则不能删除,未充值可以删除)
}
type weUserListStruct struct {
Master []WeResUserInfoStruct `json:"master"` // 自己创建的学生列表(主家长)
Slave []WeResUserInfoStruct `json:"slave"` // 添加的学生列表(副家长)
}
//type weUserListStruct struct {
// Master []WeResUserInfoStruct `json:"master"` // 自己创建的学生列表(主家长)
// Slave []WeResUserInfoStruct `json:"slave"` // 添加的学生列表(副家长)
//}
// GetStudentList 获取学生列表
// @Tags 家长微信
// @Summary 获取学生列表 [complete]
// @Description 获取学生列表
// @Product json
// @Success 0 {object} weUserListStruct
// @Success 0 {object} []weResUserInfoStruct
// @Router /we/stulist [GET]
// @Security ApiKeyAuth
func GetStudentList(c *gin.Context) {
......@@ -56,11 +57,12 @@ func GetStudentList(c *gin.Context) {
return
}
var res weUserListStruct
var res []weResUserInfoStruct
for _, cardUserID := range userInfo.MasterCardUserID {
cardUserInfo := cache.GetCardUserInfo(cardUserID)
if cardUserInfo != nil {
res.Master = append(res.Master, WeResUserInfoStruct{
res = append(res, weResUserInfoStruct{
true,
cardUserID,
cardUserInfo.Name,
cardUserInfo.Sex,
......@@ -75,7 +77,8 @@ func GetStudentList(c *gin.Context) {
for _, cardUserID := range userInfo.SlaveCardUserID {
cardUserInfo := cache.GetCardUserInfo(cardUserID)
if cardUserInfo != nil {
res.Slave = append(res.Slave, WeResUserInfoStruct{
res = append(res, weResUserInfoStruct{
false,
cardUserID,
cardUserInfo.Name,
cardUserInfo.Sex,
......
......@@ -12,26 +12,24 @@ import (
"time"
)
const tokenExpiryTimeS = uint32(48 * 3600)
const tokenExpiryTimeS = uint32(22 * 60)
type weLoginRes struct {
// weUserListStruct
// WePhone bool `json:"wePhone"` // 是否已获取到微信电话
// WeInfo bool `json:"weInfo"` // 是否已获取到微信用户信息
Token string `json:"token"`
Expiry uint32 `json:"expiry"` //到期时间,10位时间戳
WePhone bool `json:"wePhone"` // 是否已获取到微信电话,为false则需要获取
WeInfo bool `json:"weInfo"` // 是否已获取到微信用户信息,为false则需要获取
Token string `json:"token"`
Expiry uint32 `json:"expiry"` //到期时间,10位时间戳
}
type weLoginReq struct {
Nickname string `json:"nickname"` // 选填,用户昵称
AvatarURL string `json:"avatarurl" example:""` // 选填,用户头像URL
Code string `json:"code" example:"codeTest1"` //必填,登录要用的微信code
Token string `json:"token,omitempty"` //选填,如果有旧的token,也带过来
Code string `json:"code" example:"codeTest1"` //必填,登录要用的微信code
Token string `json:"token,omitempty"` //选填,如果有旧的token,也带过来
}
// WeLogin 微信登录
// @Tags 家长微信
// @Summary 登录 [complete]
// @Summary 登录(真实code) [complete]
// @Description 微信code传至后台,后台返回token,token有效时长:48小时
// @Param data body weLoginReq true "登录信息"
// @Product json
......@@ -70,11 +68,11 @@ func WeLogin(c *gin.Context) {
}
if userInfo == nil { // 微信服务器登录
unionID, err := tencent.WechatCode2Session(reqData.Code) //也不去校验reqData.Code长度了,对半是对的
if err != nil {
unionID, _, _ := tencent.WechatCode2Session(reqData.Code) //也不去校验reqData.Code长度了,对半是对的
if len(unionID) == 0 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorTencentErr,
"message": api.CodeMsg[api.ErrorTencentErr] + err.Error(),
"message": api.CodeMsg[api.ErrorTencentErr],
})
return
}
......@@ -121,25 +119,32 @@ func WeLogin(c *gin.Context) {
}
}
// 保存昵称头像
saveNickname := len(reqData.Nickname) > 0 && reqData.Nickname != userInfo.Nickname // 要更新数据
saveURL := len(reqData.AvatarURL) > 0 && reqData.AvatarURL != userInfo.AvatarURL // 要更新数据
if saveNickname || saveURL { // 要更新数据
if saveNickname {
userInfo.Nickname = reqData.Nickname
}
if saveURL {
userInfo.AvatarURL = reqData.AvatarURL
}
if dbcurd.UpdateUWeCustomerNicknameAndURL(userID, userInfo.Nickname, userInfo.AvatarURL) { // 更新数据库
cache.WechatCustomerMap.Store(userID, *userInfo) // 更新缓存
}
}
//// 保存昵称头像
//saveNickname := len(reqData.Nickname) > 0 && reqData.Nickname != userInfo.Nickname // 要更新数据
//saveURL := len(reqData.AvatarURL) > 0 && reqData.AvatarURL != userInfo.AvatarURL // 要更新数据
//
//if saveNickname || saveURL { // 要更新数据
// if saveNickname {
// userInfo.Nickname = reqData.Nickname
// }
// if saveURL {
// userInfo.AvatarURL = reqData.AvatarURL
// }
// if dbcurd.UpdateUWeCustomerNicknameAndURL(userID, userInfo.Nickname, userInfo.AvatarURL) { // 更新数据库
// cache.WechatCustomerMap.Store(userID, *userInfo) // 更新缓存
// }
//}
var res weLoginRes
res.Expiry = uint32(nowTime/1000000) + tokenExpiryTimeS
res.Token = api.CreateToken(nowTime, userID, 1, res.Expiry)
if len(userInfo.WePhone) > 0 {
res.WePhone = true
}
if len(userInfo.Nickname) > 0 && len(userInfo.AvatarURL) > 0 {
res.WeInfo = true
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
......
......@@ -15,7 +15,7 @@ import (
// PutFamilyNickName 修改亲情号的昵称
// @Tags 家长微信
// @Summary 修改亲情号的昵称(注:号码本身不可修改,只能删除和添加) [complete]
// @Summary 修改亲情号的昵称(注:号码本身不可修改,只能删除和添加,仅主家长有权限) [complete] 最新调整为仅主家长有权限
// @Description 修改亲情号接口
// @Accept json
// @Produce json
......@@ -48,7 +48,7 @@ func PutFamilyNickName(c *gin.Context) {
}
// 校验weUserID是否有cardUserID权限
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID)
if r < 2 {
if r != 2 {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorUserRole,
"data": api.CodeMsg[api.ErrorUserRole],
......
......@@ -12,18 +12,13 @@ import (
"time"
)
type BindCardUserRes struct {
GetCardUserAndTrendRes
Master bool `json:"master" example:"false"` //true:本来就是主家长,false:已成功绑定成副家长
}
// SlaveBindCardUser 通过邀请码绑定学生
// @Tags 家长微信
// @Summary 通过邀请码绑定学生 [complete]
// @Description 传学生的邀请码,后台返回学生信息
// @Produce json
// @Param share_code path string true "学生的邀请码"
// @Success 0 {object} BindCardUserRes "学生信息"
// @Success 0 {object} getCardUserAndTrendRes "学生信息"
// @Failure 30 "邀请码无效"
// @Failure 31 "邀请码已过期"
// @Router /we/bindcarduser/{share_code} [POST]
......@@ -90,14 +85,6 @@ func SlaveBindCardUser(c *gin.Context) {
})
return
}
cardUserInfo := cache.GetCardUserInfo(cardUserID)
if cardUserInfo == nil {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorShareCode,
"message": api.CodeMsg[api.ErrorShareCode],
})
return
}
// 取微信用户
v, ok := c.Get("userID")
......@@ -111,93 +98,63 @@ func SlaveBindCardUser(c *gin.Context) {
zap.Reflect("c.Get(\"userID\")", v))
return
}
if cardUserInfo.MasterWechatUserID == weUserID { // 本来就是主家长
cardUserInfo, r := cache.GetCardUserInfoAndCheckCardUserMaserAndSlaveWeID(cardUserID, weUserID)
if r < 1 { // 居然没得这个微信用户
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": BindCardUserRes{
Master: true,
GetCardUserAndTrendRes: GetCardUserAndTrendRes{
WeResUserInfoStruct: WeResUserInfoStruct{
ID: cardUserID,
Name: cardUserInfo.Name,
Sex: cardUserInfo.Sex,
Grade: cardUserInfo.Grade,
Class: cardUserInfo.Class,
StuNum: cardUserInfo.StuNum,
},
Service: [6]uint8{1, 2, 2, 2, 2, 2},
Trend: cache.GetCardUserTrendMapByCardUserID(cardUserID),
},
},
"code": api.ErrorTokenWrong,
"data": api.CodeMsg[api.ErrorTokenWrong],
})
return
}
for _, slave := range cardUserInfo.SlaveWechatUserID {
if weUserID == slave { // 本来就是副家长
var master bool
if r == 2 {
master = true
}
if r == 1 { // 还没有绑定
// 存数据库
if dbcurd.InsertOrUpdateUWeCardUserSlave(weUserID, cardUserID) == false {
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": BindCardUserRes{
Master: false,
GetCardUserAndTrendRes: GetCardUserAndTrendRes{
WeResUserInfoStruct: WeResUserInfoStruct{
ID: cardUserID,
Name: cardUserInfo.Name,
Sex: cardUserInfo.Sex,
Grade: cardUserInfo.Grade,
Class: cardUserInfo.Class,
StuNum: cardUserInfo.StuNum,
},
Service: [6]uint8{1, 2, 2, 2, 2, 2},
Trend: cache.GetCardUserTrendMapByCardUserID(cardUserID),
},
},
"code": api.ErrorSystemBusy,
"data": api.CodeMsg[api.ErrorSystemBusy],
})
return
}
}
// 存数据库
if dbcurd.InsertOrUpdateUWeCardUserSlave(weUserID, cardUserID) == false {
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemBusy,
"data": api.CodeMsg[api.ErrorSystemBusy],
})
return
}
// 存缓存
cache.InsertNewStudentIDToWechatCustomerMap(weUserID, cardUserID, false)
cache.InsertWechatAndCardUserRelationToCardUserMap(weUserID, cardUserID, false) // todo 这里可优化
// 存缓存
cache.InsertNewStudentIDToWechatCustomerMap(weUserID, cardUserID, false)
cache.InsertWechatAndCardUserRelationToCardUserMap(weUserID, cardUserID, false) // todo 这里可优化
cardUserInfo = cache.GetCardUserInfo(cardUserID) // todo 这里可优化
if cardUserInfo == nil { // 刚才都有,在就没有了呢
logger.Log.Error("SlaveBindCardUser cache.GetCardUserInfo(cardUserID) 突然没有了",
zap.Uint32("cardUserID", cardUserID),
zap.Uint32("weUserID", weUserID))
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
cardUserInfo = cache.GetCardUserInfo(cardUserID) // todo 这里可优化
if cardUserInfo == nil { // 刚才都有,在就没有了呢
logger.Log.Error("SlaveBindCardUser cache.GetCardUserInfo(cardUserID) 突然没有了",
zap.Uint32("cardUserID", cardUserID),
zap.Uint32("weUserID", weUserID))
c.JSON(http.StatusOK, gin.H{
"code": api.ErrorSystemErr,
"message": api.CodeMsg[api.ErrorSystemErr],
})
return
}
}
c.JSON(http.StatusOK, gin.H{
"code": api.Success,
"data": BindCardUserRes{
Master: false,
GetCardUserAndTrendRes: GetCardUserAndTrendRes{
WeResUserInfoStruct: WeResUserInfoStruct{
cardUserID,
cardUserInfo.Name,
cardUserInfo.Sex,
cache.GetAreaMapName(cardUserInfo.AreaID, true),
cardUserInfo.Grade,
cardUserInfo.Class,
cardUserInfo.StuNum,
},
Service: [6]uint8{1, 2, 2, 2, 2, 2},
Trend: cache.GetCardUserTrendMapByCardUserID(cardUserID),
"data": getCardUserAndTrendRes{
weResUserInfoStruct: weResUserInfoStruct{
master,
cardUserID,
cardUserInfo.Name,
cardUserInfo.Sex,
cache.GetAreaMapName(cardUserInfo.AreaID, true),
cardUserInfo.Grade,
cardUserInfo.Class,
cardUserInfo.StuNum,
},
Service: [6]uint8{1, 2, 2, 2, 2, 2},
Trend: cache.GetCardUserTrendMapByCardUserID(cardUserID),
},
})
}
......@@ -31,7 +31,7 @@ var CodeMsg = map[uint16]string{
ErrorUserRole: "用户没有权限",
ErrorSystemErr: "系统错误,请尝试重新登录(开发测试人员请联系开发人员)",
ErrorSystemBusy: "服务器忙,请重试",
ErrorTencentErr: "微信服务器返回的错误:",
ErrorTencentErr: "请求微信服务器错误,请稍后重试",
ErrorUserNotHavePhoneCard: "用户未绑定公话卡",
ErrorReqPara: "请求参数内容(取值)错误",
......
......@@ -161,12 +161,12 @@ func DecryptToken(token string) (clearStruct TokenResult) {
}
func CheckTokenExit(clearStruct *TokenResult) {
if clearStruct.UserType == 2 {
/*if clearStruct.UserType == 2 {
if clearStruct.CreatTime < cache.GetAdminTokenCreatTime(clearStruct.UserID) {
clearStruct.CheckResult = ErrorTokenExit
return
}
} else if clearStruct.UserType == 1 {
} else */if clearStruct.UserType == 1 { // 微信的做这个校验,admin那几个公共接口无所谓,缓存也不放这边
if clearStruct.CreatTime < cache.GetWechatCustomerTokenCreatTime(clearStruct.UserID) {
clearStruct.CheckResult = ErrorTokenExit
return
......
......@@ -2,12 +2,12 @@ package router
import (
"dc_golang_server_1/api"
"dc_golang_server_1/api/api_admin"
"dc_golang_server_1/api/api_public"
"dc_golang_server_1/api/api_server_ops"
"dc_golang_server_1/api/api_we"
_ "dc_golang_server_1/docs"
"dc_golang_server_1/logger"
config2 "dc_golang_server_1/util/config"
"dc_golang_server_1/util/setting"
"fmt"
"github.com/gin-gonic/gin"
"github.com/swaggo/gin-swagger"
......@@ -16,13 +16,13 @@ import (
)
func InitRouter() { //*gin.Engine{
gin.SetMode(config2.HttpServerMode)
gin.SetMode(setting.HttpServerMode)
r := gin.New()
r.Use(logger.HttpGinLog(), gin.Recovery())
r.Use(api.Cors()) //全局跨域 局部跨域的话在路由组里面去添加
//r.Use(CheckToken()) //jwt 还是在对应需要token的路由组添加
if config2.HttpServerSwagger {
if setting.HttpServerSwagger {
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
}
......@@ -37,6 +37,7 @@ func InitRouter() { //*gin.Engine{
}
r.POST("we/login/:code", api_we.WeLogin)
r.POST("we/logintest/:code", api_we.WeLoginTest)
wechat := r.Group("we/")
wechat.Use(api.JeffWTWechat())
{ // 需要token的stulist
......@@ -61,8 +62,11 @@ func InitRouter() { //*gin.Engine{
wechat.GET("phonecardstatus/:id", api_we.GetPhoneCardStatus) //获取学生公话卡状态
wechat.GET("callrecord/:id", api_we.GetCallRecord) // 查询通话记录
wechat.POST("familynum/:id", api_we.AddFamilyNum) //添加亲情号
wechat.POST("familynumtest/:id", api_we.AddFamilyNumTest) //添加亲情号
wechat.PUT("familynickname/:id", api_we.PutFamilyNickName) //修改亲情号的昵称
wechat.DELETE("familynum/:id", api_we.DeleteFamilyNum) //删除亲情号
wechat.POST("webindphone", api_we.WechatUserBindWePhone) //上传微信用户手机号
wechat.POST("webindinfo", api_we.WechatUserBindWeInfo) //上传微信用户信息
//缴费
//查询缴费记录
......@@ -72,17 +76,23 @@ func InitRouter() { //*gin.Engine{
//查询缴费记录
}
// r.POST("ad/login", api_we.AdminLogin)
admin := r.Group("ad/")
// admin.Use(api.JeffWTAdmin())
//// r.POST("ad/login", api_we.AdminLogin)
//admin := r.Group("ad/")
//// admin.Use(api.JeffWTAdmin())
//{
// admin.POST("area", api_admin.CreateArea) // 新建一个学校
// // admin.GET("cache", api_cache.GetCacheMap) // 获取缓存内容
//}
serverOps := r.Group("server/")
// serverOps.Use(api.JeffWTAdmin())
{
admin.POST("area", api_admin.CreateArea) // 新建一个学校
// admin.GET("cache", api_cache.GetCacheMap) // 获取缓存内容
serverOps.GET("goroutinenum", api_server_ops.GetSystemRunPara) // 获取当前系统运行状态
}
fmt.Println(time.Now(), "server is running:swagger", config2.HttpServerSwagger)
fmt.Println(time.Now(), "server is running:swagger", setting.HttpServerSwagger)
err := r.Run(config2.HttpServerPort)
err := r.Run(setting.HttpServerPort)
if err != nil {
panic(err)
}
......
......@@ -15,8 +15,6 @@ func Init() {
initSimInfoMap()
initAreaServiceMap()
initPhone20DeviceMap()
// initAdminMap()
// initOperatorMap()
initCardUserTrendMap()
}
......@@ -34,35 +32,19 @@ var CountyMap sync.Map // 区县列表map[uint32][]model.C
var CountyAreaMap sync.Map //map[uint32][[]uint32] 区县ID作为KEY,[]area_id 作为Value
// var LockCountyAreaMap bool // todo 正规的做法是用 map[区县ID]bool
// TestAreaMap /******************************************************************测试校区列表**/
// AreaMap /******************************************************区域(校区)**/
var AreaMap sync.Map //area_id 作为KEY CacheBAreaStruct 作为VALUE
//type CacheBAreaStruct struct { // CacheBAreaStruct 区域信息缓存,通过区域ID查出
// Name string
// Longitude uint32
// Latitude uint32
// CountyID uint32
// AreaService []uint32
//// CountyID uint32
//// AreaService []uint32
// Status uint8 //校区状态 0 不展示 1展示 2测试校区
//}
// var LockAreaMapAreaService bool todo
/*********************************************************代理商**/
//// AgentMap 代理商
//var AgentMap sync.Map
/*---------------------------------------------------------------*/
/*********************************************************运营商**/
//var operatorMap sync.Map //运营商id作为KEY
//type OperatorStruct struct {
// ShortName string
// // 可再添加运营商属性
//}
/*---------------------------------------------------------------*/
/******************************************************区域(校区)服务信息**/
var areaServiceMap sync.Map //area_service_id 作为KEY CacheBAreaStruct 作为VALUE //status不为0的所有校区服务
//type AreaServiceStruct struct { // 后续再加支付信息
......@@ -75,22 +57,6 @@ var areaServiceMap sync.Map //area_service_id 作为KEY CacheBAreaStruct 作为
/*---------------------------------------------------------------*/
/******************************************************后台管理用户**/
//var adminMap sync.Map //后台管理用户 LoginAccount(string) 作为KEY
//type AdminStruct struct {
// Password [16]byte
// tokenCreatTime int64 // 初始化为0,则已有的token还有效
// Name string
// upAdminID uint32
// //Phone string
// //OperatorID []int
// SystemAuth uint32 //系统角色权限
// AreaServiceAuth [][]uint32 //area_service_id,admin_role_id
//}
// todo 加锁var LockAreaMapAreaService bool
/*---------------------------------------------------------------*/
// roleAuthMap /****************************角色权限(包含区域和系统角色)*/
//var adminRoleAuthMap sync.Map //admin_role_id 作为KEY
//type RoleAuthStruct struct {
......
package cache
func initAdminMap() {
// todo
}
func GetAdminTokenCreatTime(adminID uint32) int64 {
return 0xffffffff //没有这个用户返回0xffffffff
}
func UpdateAdminTokenCreatTime(adminID uint32, createAt int64) {
}
......@@ -32,20 +32,29 @@ func initAreaMapAndCountyAreaMap() {
log.Panicln("SelectAreaToMap rows", err)
}
defer rows.Close()
var countyID uint32
for rows.Next() {
err = rows.Scan(&areaID, &temp.CountyID, &temp.Name, &temp.Longitude, &temp.Latitude, &temp.Status)
//err = rows.Scan(&areaID, &temp.CountyID, &temp.Name, &temp.Longitude, &temp.Latitude, &temp.Status)
err = rows.Scan(&areaID, &countyID, &temp.Name, &temp.Longitude, &temp.Latitude, &temp.Status)
if err != nil {
log.Panicln("SelectAreaToMap rows.Scan", err)
}
AreaMap.Store(areaID, temp)
if temp.CountyID != 0 {
//if temp.CountyID != 0 {
// var areaIDList []uint32
// if v, ok := CountyAreaMap.Load(temp.CountyID); ok {
// areaIDList, _ = v.([]uint32)
// }
// areaIDList = append(areaIDList, areaID)
// CountyAreaMap.Store(temp.CountyID, areaIDList)
//}
if countyID != 0 {
var areaIDList []uint32
if v, ok := CountyAreaMap.Load(temp.CountyID); ok {
if v, ok := CountyAreaMap.Load(countyID); ok {
areaIDList, _ = v.([]uint32)
}
areaIDList = append(areaIDList, areaID)
CountyAreaMap.Store(temp.CountyID, areaIDList)
CountyAreaMap.Store(countyID, areaIDList)
}
}
// 处理完毕后,需要判断一次遍历过程中是否有错误产生
......
package dbcurd
import (
"dc_golang_server_1/logger"
"go.uber.org/zap"
"strings"
)
//id integer NOT NULL DEFAULT nextval('b_area_id_seq'::regclass),
//county_id integer,
//name character varying(32) COLLATE pg_catalog."default",
//longitude integer,
//latitude integer,
//status smallint,
//creator_id integer,
//updater_id integer,
//create_at timestamp without time zone,
//update_at timestamp without time zone,
//CONSTRAINT b_area_pkey PRIMARY KEY (id),
//CONSTRAINT b_area_uniq1 UNIQUE (name)
type TableBaseArea struct {
ID uint32 `swaggerignore:"true"`
CountyID uint32 `json:"county_id" example:"2725"` // 必填,所属区县ID
Name string `json:"name" example:"多彩温江校区"` // 必填,名字
Longitude uint32 `json:"longitude" example:"103000000"` // 必填,经度
Latitude uint32 `json:"latitude" example:"30000000"` // 必填,纬度
Status uint8 `json:"status" example:"1"` // 必填,是否测试校区,0预留 1正示 2测试校区
CreatorID uint32 `json:"creator_id" example:"1"` // 测试用,以后不传这个字段
// UpdaterID uint32
// CreateAt time.Time
// UpdateAt time.Time
}
func InsertBaseArea(insertData *TableBaseArea) uint8 { //0 成功 1 唯一约束重复 9 系统繁忙
err := PgDb.QueryRow("INSERT INTO b_area(county_id,name,longitude,latitude,status,creator_id)VALUES($1,$2,$3,$4,$5,$6)RETURNING id",
insertData.CountyID,
insertData.Name,
insertData.Longitude,
insertData.Latitude,
insertData.Status,
insertData.CreatorID,
).Scan(&insertData.ID)
if err == nil {
return 0
}
if strings.Contains(err.Error(), "duplicate key value") {
logger.Log.Error("InsertBaseArea duplicate key value",
zap.Reflect("insertData", insertData),
zap.Error(err))
return 1
}
logger.Log.Error("InsertBaseArea Err",
zap.Reflect("insertData", insertData),
zap.Error(err))
return 9
}
////id integer NOT NULL DEFAULT nextval('b_area_id_seq'::regclass),
////county_id integer,
////name character varying(32) COLLATE pg_catalog."default",
////longitude integer,
////latitude integer,
////status smallint,
////creator_id integer,
////updater_id integer,
////create_at timestamp without time zone,
////update_at timestamp without time zone,
////CONSTRAINT b_area_pkey PRIMARY KEY (id),
////CONSTRAINT b_area_uniq1 UNIQUE (name)
//
//type TableBaseArea struct {
// ID uint32 `swaggerignore:"true"`
// CountyID uint32 `json:"county_id" example:"2725"` // 必填,所属区县ID
// Name string `json:"name" example:"多彩温江校区"` // 必填,名字
// Longitude uint32 `json:"longitude" example:"103000000"` // 必填,经度
// Latitude uint32 `json:"latitude" example:"30000000"` // 必填,纬度
// Status uint8 `json:"status" example:"1"` // 必填,是否测试校区,0预留 1正示 2测试校区
// CreatorID uint32 `json:"creator_id" example:"1"` // 测试用,以后不传这个字段
// // UpdaterID uint32
// // CreateAt time.Time
// // UpdateAt time.Time
//}
//
//func InsertBaseArea(insertData *TableBaseArea) uint8 { //0 成功 1 唯一约束重复 9 系统繁忙
// err := PgDb.QueryRow("INSERT INTO b_area(county_id,name,longitude,latitude,status,creator_id)VALUES($1,$2,$3,$4,$5,$6)RETURNING id",
// insertData.CountyID,
// insertData.Name,
// insertData.Longitude,
// insertData.Latitude,
// insertData.Status,
// insertData.CreatorID,
// ).Scan(&insertData.ID)
// if err == nil {
// return 0
// }
// if strings.Contains(err.Error(), "duplicate key value") {
// logger.Log.Error("InsertBaseArea duplicate key value",
// zap.Reflect("insertData", insertData),
// zap.Error(err))
// return 1
// }
// logger.Log.Error("InsertBaseArea Err",
// zap.Reflect("insertData", insertData),
// zap.Error(err))
// return 9
//}
......@@ -3,7 +3,7 @@ package dbcurd
import (
"database/sql"
"dc_golang_server_1/logger"
"dc_golang_server_1/util/config"
"dc_golang_server_1/util/setting"
"fmt"
_ "github.com/lib/pq"
"go.uber.org/zap"
......@@ -24,8 +24,8 @@ var stmtUpdateWechatUserLogin *sql.Stmt // 微信登录时间和登录次数更
func InitDb() {
var err error
fmt.Println("DBDSN", config.DbDSN)
PgDb, err = sql.Open("postgres", config.DbDSN)
fmt.Println("DBDSN", setting.DbDSN)
PgDb, err = sql.Open("postgres", setting.DbDSN)
if err != nil {
panic("数据库连接失败" + err.Error())
}
......
......@@ -126,7 +126,7 @@ func SelectCardUserTrendsLimit20FromUCallRecordByCardUserID(cardUserID uint32) (
//TalkTime uint8 `json:"time"` // 通话时长,单位(分钟)
func SelectWeGetCallRecord(cardUserID uint32, startTime, endTime, desc string, pNum, pSize uint64) (callRecord []model.SelectWeGetCallRecordStruct) {
sql := "SELECT call_start_at,called_number,called_nickname,(talk_time+59)/60,place_user FROM public.u_call_record WHERE card_user_id=$1" // 后面分表后看情况优化,现在第一筛选条件为card_user_id我认为更好
sql := "SELECT call_start_at,called_number,called_nickname,(talk_time+59)/60,place_user FROM u_call_record WHERE card_user_id=$1" // 后面分表后看情况优化,现在第一筛选条件为card_user_id我认为更好
if len(startTime) > 0 && len(endTime) > 0 {
sql += " AND call_start_at BETWEEN'" + startTime + "'AND'" + endTime + "'"
}
......@@ -147,12 +147,14 @@ func SelectWeGetCallRecord(cardUserID uint32, startTime, endTime, desc string, p
callRecord = make([]model.SelectWeGetCallRecordStruct, 0)
var temp model.SelectWeGetCallRecordStruct
var callStartAt time.Time
for rows.Next() {
err = rows.Scan(&temp.CallStartAt, &temp.CalledNumber, &temp.CalledNickname, &temp.TalkTime, &temp.Place)
err = rows.Scan(&callStartAt, &temp.CalledNumber, &temp.CalledNickname, &temp.TalkTime, &temp.Place)
if err != nil {
fmt.Println("SelectWeGetCallRecord", sql, err)
return
}
temp.CallStartAt = callStartAt.Format("2006-01-02 15:04:05")
callRecord = append(callRecord, temp)
}
// 处理完毕后,需要判断一次遍历过程中是否有错误产生
......
......@@ -11,7 +11,7 @@ import (
func SelectUSimFamilyNumBySimID(simID string) (familyNumbers []model.CacheFamilyOnePerson) {
var onePerson model.CacheFamilyOnePerson
familyNumbers = make([]model.CacheFamilyOnePerson, 0)
rows, err := PgDb.Query("SELECT phone,nickname FROM u_sim_family_num WHERE sim_id=$1 order by create_at", simID)
rows, err := PgDb.Query("SELECT phone,nickname FROM u_sim_family_num WHERE sim_id=$1 AND delete_at is null order by create_at", simID)
if err != nil {
logger.Log.Error("SelectUSimFamilyNumBySimID 1",
zap.String("simID", simID),
......@@ -42,7 +42,7 @@ func SelectUSimFamilyNumBySimID(simID string) (familyNumbers []model.CacheFamily
func InsertUSimFamilyNum(simID, phone, nickname string) uint8 {
var err error
for i := 0; i < 50; i++ {
_, err = PgDb.Exec("INSERT INTO u_sim_family_num(sim_id,phone,nickname)VALUES($1,$2,$3)", simID, phone, nickname)
_, err = PgDb.Exec("INSERT INTO u_sim_family_num(sim_id,phone,nickname)VALUES($1,$2,$3)ON CONFLICT ON CONSTRAINT u_sim_family_num_pkey DO UPDATE SET nickname=$3,delete_at=null", simID, phone, nickname)
if err == nil {
return InsertOK
}
......@@ -69,16 +69,17 @@ func UpdateUSimFamilyNumNickname(simID, phone, nickname string) bool {
return false
}
func DeleteUSimFamilyNum(simID, phone string) bool {
func UpdateUSimFamilyNumDeleteAt(simID, phone string) bool {
var err error
for i := 0; i < 50; i++ {
_, err = PgDb.Exec("DELETE FROM u_sim_family_num WHERE sim_id=$1 AND phone=$2", simID, phone)
// _, err = PgDb.Exec("DELETE FROM u_sim_family_num WHERE sim_id=$1 AND phone=$2", simID, phone)
_, err = PgDb.Exec("UPDATE u_sim_family_num SET delete_at=$1 WHERE sim_id=$2 AND phone=$3", time.Now().Format("2006-01-02 15:04:05.000"), simID, phone)
if err == nil {
return true
}
time.Sleep(2 * time.Millisecond)
}
logger.Log.Error("DeleteUSimFamilyNum Err",
logger.Log.Error("UpdateUSimFamilyNumDeleteAt Err",
zap.String("simID", simID),
zap.String("phone", phone),
zap.Error(err))
......
......@@ -162,3 +162,18 @@ func UpdateUWeCustomerNicknameAndURL(weUserID uint32, nickname, url string) bool
zap.Error(err))
return false
}
func UpdateUWeCustomerWePhone(weUserID uint32, phone string) bool { // todo 看下用不用搞成 *sql.Stmt
var err error
for i := 0; i < 10; i++ {
if _, err = PgDb.Exec("UPDATE u_we_customer SET phone=$1 WHERE id=$2", phone, weUserID); err == nil {
return true
}
time.Sleep(2 * time.Millisecond)
}
logger.Log.Error("UpdateUWeCustomerWePhone",
zap.String("phone", phone),
zap.Uint32("weUserID", weUserID),
zap.Error(err))
return false
}
......@@ -9,12 +9,12 @@ type CacheBDistrictStruct struct {
}
type CacheBAreaStruct struct { // CacheBAreaStruct 区域信息缓存,通过区域ID查出,后续再加支付信息
Name string
Longitude uint32
Latitude uint32
CountyID uint32
AreaService []uint32
Status uint8 //校区状态 0 不展示 1展示 2测试校区
Name string
Longitude uint32
Latitude uint32
// CountyID uint32
// AreaService []uint32
Status uint8 //校区状态 0 不展示 1展示 2测试校区
}
type CacheAreaServiceStruct struct { // 后续再加支付信息
......
No preview for this file type
No preview for this file type
package dcphone20
import (
config2 "dc_golang_server_1/util/config"
config2 "dc_golang_server_1/util/setting"
)
var TCP DCPhone20
func NewDCPhone20() {
var dcPhone20TCP DCPhone20
dcPhone20TCP.NewDCPhone20("DCRYM-2018-pswd.", "I can't tell YOU", 0x5B) // config
dcPhone20TCP.TCPStart(config2.TcpLongPort)
// dcPhone10TCP.NewDCPhone20API(r)
// var DcPhone20TCP DCPhone20
TCP.NewDCPhone20("DCRYM-2018-pswd.", "I can't tell YOU", 0x5B) // setting
TCP.TCPStart(config2.TcpLongPort)
}
......@@ -11,7 +11,6 @@ import (
"go.uber.org/zap"
"strconv"
"strings"
"sync"
"time"
)
......@@ -40,7 +39,7 @@ type DevStateStruct struct {
type DCPhone20 struct {
devproduct.DCLongTCPHex
MapDCPhone10State sync.Map
// MapDCPhone10State sync.Map
}
func (dev *DCPhone20) NewDCPhone20(password string, iv string, devType uint8) {
......@@ -73,7 +72,7 @@ func (dev *DCPhone20) response(data *devproduct.HexData) {
// }{ip, port},
//}
//x, _ := json.Marshal(jsonStruct)
//_, _ = jeffhttprequest.Post(config.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
//_, _ = jeffhttprequest.Post(setting.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
} else {
logger.Log.Error("data.Length error",
zap.String("Src", "TCP-SERVER-response"),
......@@ -93,7 +92,7 @@ func (dev *DCPhone20) response(data *devproduct.HexData) {
// }{uint16(data.Data[0]) + (uint16(data.Data[1]) << 8), data.Data[2]},
//}
//x, _ := json.Marshal(jsonStruct)
//_, _ = jeffhttprequest.Post(config.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
//_, _ = jeffhttprequest.Post(setting.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
} else {
logger.Log.Error("data.Length error",
zap.String("Src", "TCP-SERVER-response"),
......@@ -112,7 +111,7 @@ func (dev *DCPhone20) response(data *devproduct.HexData) {
// data.Data[0],
//}
//x, _ := json.Marshal(jsonStruct)
//_, _ = jeffhttprequest.Post(config.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
//_, _ = jeffhttprequest.Post(setting.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
} else {
logger.Log.Error("data.Length error",
zap.String("Src", "TCP-SERVER-response"),
......@@ -140,7 +139,7 @@ func (dev *DCPhone20) response(data *devproduct.HexData) {
//}
//
//x, _ := json.Marshal(jsonStruct)
//_, _ = jeffhttprequest.Post(config.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
//_, _ = jeffhttprequest.Post(setting.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
} else {
logger.Log.Error("data.Length error",
zap.String("Src", "TCP-SERVER-response"),
......@@ -195,7 +194,7 @@ func (dev *DCPhone20) response(data *devproduct.HexData) {
//}
//jsonStruct.Value = workTimeTemp
//x, _ := json.Marshal(jsonStruct)
//_, _ = jeffhttprequest.Post(config.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
//_, _ = jeffhttprequest.Post(setting.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
case 0x0a | 0x80: // "key_password", // 最长10个字符(数字加*#)
//jsonStruct := paraOneString{
// data.TimeUtc,
......@@ -203,7 +202,7 @@ func (dev *DCPhone20) response(data *devproduct.HexData) {
// string(data.Data),
//}
//x, _ := json.Marshal(jsonStruct)
//_, _ = jeffhttprequest.Post(config.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
//_, _ = jeffhttprequest.Post(setting.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
// 设备控制类ctrl
case 0x32 | 0x80: // 0x32|0x80:"ctrl/restart_device", // 重启设备 上下行均空
......@@ -212,7 +211,7 @@ func (dev *DCPhone20) response(data *devproduct.HexData) {
// []uint32{data.DevID},
//}
//x, _ := json.Marshal(jsonStruct)
//_, _ = jeffhttprequest.Post(config.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
//_, _ = jeffhttprequest.Post(setting.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
case 0x70 | 0x80: // 0x70|0x80:"ctrl/read_firmware_version", // 读取固件版本
if data.Length > 22 {
//jsonStruct := devUpFirmwareInfo{
......@@ -229,7 +228,7 @@ func (dev *DCPhone20) response(data *devproduct.HexData) {
// },
//}
//x, _ := json.Marshal(jsonStruct)
//_, _ = jeffhttprequest.Post(config.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
//_, _ = jeffhttprequest.Post(setting.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
} else {
logger.Log.Error("data.Length error",
zap.String("Src", "TCP-SERVER-response"),
......@@ -262,7 +261,7 @@ func (dev *DCPhone20) response(data *devproduct.HexData) {
//}
//
//x, _ := json.Marshal(jsonStruct)
//_, _ = jeffhttprequest.Post(config.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
//_, _ = jeffhttprequest.Post(setting.HttpClientBaseUrl+httpParaNameMapHex2String[ctrlCode], x)
} else {
logger.Log.Error("data.Length error",
zap.String("Src", "TCP-SERVER-response"),
......
......@@ -3,7 +3,7 @@ package devproduct
import (
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/logger"
config2 "dc_golang_server_1/util/config"
config2 "dc_golang_server_1/util/setting"
"go.uber.org/zap"
"net"
"strconv"
......@@ -181,7 +181,7 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall
if err != nil {
// fmt.Println("conn.Read:", err)
// logger debug 其中存在超时,或新连接来关闭了旧链接
logger.Log.Debug("read error",
logger.Log.Info("read error",
zap.String("Src", "TCP-SERVER-connectionHandle"),
zap.Uint32("DevID", myDevID),
zap.String("Conn", conn.RemoteAddr().String()),
......
......@@ -23,45 +23,6 @@ var doc = `{
"host": "{{.Host}}",
"basePath": "{{.BasePath}}",
"paths": {
"/ad/area": {
"post": {
"security": [
{
"ApiKeyAuth": []
}
],
"description": "目前仅用于填充数据,暂未做权限校验",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"管理后台"
],
"summary": "创建一个学校",
"parameters": [
{
"description": "学校信息",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/dbcurd.TableBaseArea"
}
}
],
"responses": {
"0": {
"description": "",
"schema": {
"type": "integer"
}
}
}
}
},
"/base/city/{provinceID}": {
"get": {
"security": [
......@@ -233,6 +194,28 @@ var doc = `{
}
}
},
"/server/goroutinenum": {
"get": {
"security": [
{
"ApiKeyAuth": []
}
],
"description": "返回当前程序运行状态",
"tags": [
"运维"
],
"summary": "获取当前程序运行状态",
"responses": {
"0": {
"description": "程序运行状态",
"schema": {
"$ref": "#/definitions/api_server_ops.apiGetSystemRunParaStruct"
}
}
}
}
},
"/we/bindcarduser/{id}": {
"get": {
"security": [
......@@ -327,7 +310,7 @@ var doc = `{
"0": {
"description": "学生信息",
"schema": {
"$ref": "#/definitions/api_we.BindCardUserRes"
"$ref": "#/definitions/api_we.getCardUserAndTrendRes"
}
},
"30": {
......@@ -684,7 +667,7 @@ var doc = `{
"0": {
"description": "学生信息和最新动态",
"schema": {
"$ref": "#/definitions/api_we.GetCardUserAndTrendRes"
"$ref": "#/definitions/api_we.getCardUserAndTrendRes"
}
}
}
......@@ -707,7 +690,7 @@ var doc = `{
"tags": [
"家长微信"
],
"summary": "修改亲情号的昵称(注:号码本身不可修改,只能删除和添加) [complete]",
"summary": "修改亲情号的昵称(注:号码本身不可修改,只能删除和添加,仅主家长有权限) [complete] 最新调整为仅主家长有权限",
"parameters": [
{
"type": "integer",
......@@ -750,7 +733,7 @@ var doc = `{
"tags": [
"家长微信"
],
"summary": "添加亲情号 [complete]",
"summary": "添加亲情号(仅主家长有权限) [complete] 最新调整为仅主家长有权限",
"parameters": [
{
"type": "integer",
......@@ -791,7 +774,7 @@ var doc = `{
"tags": [
"家长微信"
],
"summary": "删除亲情号 [complete]",
"summary": "删除亲情号(仅主家长有权限) [complete] 最新调整为仅主家长有权限",
"parameters": [
{
"type": "integer",
......@@ -817,13 +800,84 @@ var doc = `{
}
}
},
"/we/familynumtest/{id}": {
"post": {
"security": [
{
"ApiKeyAuth": []
}
],
"description": "家长绑定亲情号接口",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"家长微信"
],
"summary": "添加亲情号(仅主家长有权限) [complete] 用于测试卡的添加,当前测试卡\"89861120040280843640\"",
"parameters": [
{
"type": "integer",
"description": "学生ID",
"name": "id",
"in": "path",
"required": true
},
{
"description": "亲情号内容",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/model.CacheFamilyOnePerson"
}
}
],
"responses": {
"0": {
"description": ""
}
}
}
},
"/we/login/{code}": {
"post": {
"description": "微信code传至后台,后台返回token,token有效时长:48小时",
"tags": [
"家长微信"
],
"summary": "登录 [complete]",
"summary": "登录(真实code) [complete]",
"parameters": [
{
"description": "登录信息",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_we.weLoginReq"
}
}
],
"responses": {
"0": {
"description": "",
"schema": {
"$ref": "#/definitions/api_we.weLoginRes"
}
}
}
}
},
"/we/logintest/{code}": {
"post": {
"description": "微信code传至后台,后台返回token,token有效时长:48小时",
"tags": [
"家长微信"
],
"summary": "登录(测试的假code) [complete]",
"parameters": [
{
"description": "登录信息",
......@@ -1016,7 +1070,10 @@ var doc = `{
"0": {
"description": "",
"schema": {
"$ref": "#/definitions/api_we.weUserListStruct"
"type": "array",
"items": {
"$ref": "#/definitions/api_we.weResUserInfoStruct"
}
}
}
}
......@@ -1055,6 +1112,72 @@ var doc = `{
}
}
}
},
"/we/webindinfo": {
"post": {
"security": [
{
"ApiKeyAuth": []
}
],
"description": "上传用户授权获取到的微信头像昵称",
"produces": [
"application/json"
],
"tags": [
"家长微信"
],
"summary": "上传微信用户头像昵称 [complete]",
"parameters": [
{
"description": "头像昵称信息",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_we.wechatUserBindWeInfoStruct"
}
}
],
"responses": {
"0": {
"description": ""
}
}
}
},
"/we/webindphone": {
"post": {
"security": [
{
"ApiKeyAuth": []
}
],
"description": "上传用户授权获取到的微信手机号",
"produces": [
"application/json"
],
"tags": [
"家长微信"
],
"summary": "上传微信用户手机号 [complete]",
"parameters": [
{
"description": "手机号",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_we.wechatUserBindWePhoneStruct"
}
}
],
"responses": {
"0": {
"description": ""
}
}
}
}
},
"definitions": {
......@@ -1088,116 +1211,17 @@ var doc = `{
}
}
},
"api_we.BindCardUserRes": {
"api_server_ops.apiGetSystemRunParaStruct": {
"type": "object",
"properties": {
"area": {
"description": "区域名字",
"type": "string",
"example": "温江实验中学"
},
"class": {
"description": "0无意义",
"goroutineNum": {
"type": "integer"
},
"grade": {
"description": "0无意义 \"1~9对应一年级~九年级,10~12对应高一~高三\"",
"numCPU": {
"type": "integer"
},
"id": {
"description": "学生ID",
"phoneTcpSocketNum": {
"type": "integer"
},
"master": {
"description": "true:本来就是主家长,false:已成功绑定成副家长",
"type": "boolean",
"example": false
},
"name": {
"type": "string"
},
"service": {
"description": "对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)",
"type": "array",
"items": {
"type": "integer"
},
"example": [
1,
2,
2,
0,
0,
0
]
},
"sex": {
"description": "0无意义 1女 2男",
"type": "integer"
},
"stuNum": {
"description": "\"\"无意义",
"type": "string"
},
"trend": {
"type": "array",
"items": {
"$ref": "#/definitions/model.CacheCardUserTrendStruct"
}
}
}
},
"api_we.GetCardUserAndTrendRes": {
"type": "object",
"properties": {
"area": {
"description": "区域名字",
"type": "string",
"example": "温江实验中学"
},
"class": {
"description": "0无意义",
"type": "integer"
},
"grade": {
"description": "0无意义 \"1~9对应一年级~九年级,10~12对应高一~高三\"",
"type": "integer"
},
"id": {
"description": "学生ID",
"type": "integer"
},
"name": {
"type": "string"
},
"service": {
"description": "对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)",
"type": "array",
"items": {
"type": "integer"
},
"example": [
1,
2,
2,
0,
0,
0
]
},
"sex": {
"description": "0无意义 1女 2男",
"type": "integer"
},
"stuNum": {
"description": "\"\"无意义",
"type": "string"
},
"trend": {
"type": "array",
"items": {
"$ref": "#/definitions/model.CacheCardUserTrendStruct"
}
}
}
},
......@@ -1221,6 +1245,10 @@ var doc = `{
"description": "学生ID",
"type": "integer"
},
"master": {
"description": "是否为主家长",
"type": "boolean"
},
"name": {
"type": "string"
},
......@@ -1249,39 +1277,6 @@ var doc = `{
}
}
},
"api_we.WeResUserInfoStruct": {
"type": "object",
"properties": {
"area": {
"description": "区域名字",
"type": "string",
"example": "温江实验中学"
},
"class": {
"description": "0无意义",
"type": "integer"
},
"grade": {
"description": "0无意义 \"1~9对应一年级~九年级,10~12对应高一~高三\"",
"type": "integer"
},
"id": {
"description": "学生ID",
"type": "integer"
},
"name": {
"type": "string"
},
"sex": {
"description": "0无意义 1女 2男",
"type": "integer"
},
"stuNum": {
"description": "\"\"无意义",
"type": "string"
}
}
},
"api_we.apiCardBindStruct": {
"type": "object",
"properties": {
......@@ -1339,6 +1334,64 @@ var doc = `{
}
}
},
"api_we.getCardUserAndTrendRes": {
"type": "object",
"properties": {
"area": {
"description": "区域名字",
"type": "string",
"example": "温江实验中学"
},
"class": {
"description": "0无意义",
"type": "integer"
},
"grade": {
"description": "0无意义 \"1~9对应一年级~九年级,10~12对应高一~高三\"",
"type": "integer"
},
"id": {
"description": "学生ID",
"type": "integer"
},
"master": {
"description": "是否为主家长",
"type": "boolean"
},
"name": {
"type": "string"
},
"service": {
"description": "对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)",
"type": "array",
"items": {
"type": "integer"
},
"example": [
1,
2,
2,
0,
0,
0
]
},
"sex": {
"description": "0无意义 1女 2男",
"type": "integer"
},
"stuNum": {
"description": "\"\"无意义",
"type": "string"
},
"trend": {
"type": "array",
"items": {
"$ref": "#/definitions/model.CacheCardUserTrendStruct"
}
}
}
},
"api_we.getPhoneCardStatusRes": {
"type": "object",
"properties": {
......@@ -1412,19 +1465,11 @@ var doc = `{
"api_we.weLoginReq": {
"type": "object",
"properties": {
"avatarurl": {
"description": "选填,用户头像URL",
"type": "string"
},
"code": {
"description": "必填,登录要用的微信code",
"type": "string",
"example": "codeTest1"
},
"nickname": {
"description": "选填,用户昵称",
"type": "string"
},
"token": {
"description": "选填,如果有旧的token,也带过来",
"type": "string"
......@@ -1439,62 +1484,79 @@ var doc = `{
"type": "integer"
},
"token": {
"description": "weUserListStruct\nWePhone bool ` + "`" + `json:\"wePhone\"` + "`" + ` // 是否已获取到微信电话\nWeInfo bool ` + "`" + `json:\"weInfo\"` + "`" + ` // 是否已获取到微信用户信息",
"type": "string"
},
"weInfo": {
"description": "是否已获取到微信用户信息,为false则需要获取",
"type": "boolean"
},
"wePhone": {
"description": "weUserListStruct",
"type": "boolean"
}
}
},
"api_we.weUserListStruct": {
"api_we.weResUserInfoStruct": {
"type": "object",
"properties": {
"area": {
"description": "区域名字",
"type": "string",
"example": "温江实验中学"
},
"class": {
"description": "0无意义",
"type": "integer"
},
"grade": {
"description": "0无意义 \"1~9对应一年级~九年级,10~12对应高一~高三\"",
"type": "integer"
},
"id": {
"description": "学生ID",
"type": "integer"
},
"master": {
"description": "自己创建的学生列表(主家长)",
"type": "array",
"items": {
"$ref": "#/definitions/api_we.WeResUserInfoStruct"
}
"description": "是否为主家长",
"type": "boolean"
},
"slave": {
"description": "添加的学生列表(副家长)",
"type": "array",
"items": {
"$ref": "#/definitions/api_we.WeResUserInfoStruct"
}
"name": {
"type": "string"
},
"sex": {
"description": "0无意义 1女 2男",
"type": "integer"
},
"stuNum": {
"description": "\"\"无意义",
"type": "string"
}
}
},
"dbcurd.TableBaseArea": {
"api_we.wechatUserBindWeInfoStruct": {
"type": "object",
"properties": {
"county_id": {
"description": "必填,所属区县ID",
"type": "integer",
"example": 2725
},
"creator_id": {
"description": "测试用,以后不传这个字段",
"type": "integer",
"example": 1
},
"latitude": {
"description": "必填,纬度",
"type": "integer",
"example": 30000000
"avatarurl": {
"description": "用户头像URL",
"type": "string"
},
"longitude": {
"description": "必填,经度",
"type": "integer",
"example": 103000000
"nickname": {
"description": "用户昵称",
"type": "string"
}
}
},
"api_we.wechatUserBindWePhoneStruct": {
"type": "object",
"properties": {
"code": {
"type": "string"
},
"name": {
"description": "必填,名字",
"type": "string",
"example": "多彩温江校区"
"encryptedData": {
"type": "string"
},
"status": {
"description": "必填,是否测试校区,0预留 1正示 2测试校区",
"type": "integer",
"example": 1
"iv": {
"type": "string"
}
}
},
......@@ -1625,12 +1687,12 @@ type swaggerInfo struct {
// SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = swaggerInfo{
Version: "V0.0.0.1",
Version: "V0.0.2",
Host: "",
BasePath: "/",
Schemes: []string{},
Title: "多彩中小学一卡通系统",
Description: "用于家长端微信小程序及web端管理后台",
Description: "2021-10-31-V0.0.2 添加、删除亲情号以及修改亲情号昵称调整为仅主家长有权限,免得副家长随便改浪费移动的次数\n2021-11-01 1. 登录接口不再上传昵称头像 2. 增加上传微信昵称头像接口和上传微信绑定手机号接口\n2021-11-01 15:30 1. 学生列表接口返回内容小调整 2. 学生信息返回内容增加master字段",
}
type s struct{}
......@@ -1665,5 +1727,5 @@ func (s *s) ReadDoc() string {
}
func init() {
swag.Register(swag.Name, &s{})
swag.Register("swagger", &s{})
}
{
"swagger": "2.0",
"info": {
"description": "用于家长端微信小程序及web端管理后台",
"description": "2021-10-31-V0.0.2 添加、删除亲情号以及修改亲情号昵称调整为仅主家长有权限,免得副家长随便改浪费移动的次数\n2021-11-01 1. 登录接口不再上传昵称头像 2. 增加上传微信昵称头像接口和上传微信绑定手机号接口\n2021-11-01 15:30 1. 学生列表接口返回内容小调整 2. 学生信息返回内容增加master字段",
"title": "多彩中小学一卡通系统",
"contact": {},
"version": "V0.0.0.1"
"version": "V0.0.2"
},
"basePath": "/",
"paths": {
"/ad/area": {
"post": {
"security": [
{
"ApiKeyAuth": []
}
],
"description": "目前仅用于填充数据,暂未做权限校验",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"管理后台"
],
"summary": "创建一个学校",
"parameters": [
{
"description": "学校信息",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/dbcurd.TableBaseArea"
}
}
],
"responses": {
"0": {
"description": "",
"schema": {
"type": "integer"
}
}
}
}
},
"/base/city/{provinceID}": {
"get": {
"security": [
......@@ -218,6 +179,28 @@
}
}
},
"/server/goroutinenum": {
"get": {
"security": [
{
"ApiKeyAuth": []
}
],
"description": "返回当前程序运行状态",
"tags": [
"运维"
],
"summary": "获取当前程序运行状态",
"responses": {
"0": {
"description": "程序运行状态",
"schema": {
"$ref": "#/definitions/api_server_ops.apiGetSystemRunParaStruct"
}
}
}
}
},
"/we/bindcarduser/{id}": {
"get": {
"security": [
......@@ -312,7 +295,7 @@
"0": {
"description": "学生信息",
"schema": {
"$ref": "#/definitions/api_we.BindCardUserRes"
"$ref": "#/definitions/api_we.getCardUserAndTrendRes"
}
},
"30": {
......@@ -669,7 +652,7 @@
"0": {
"description": "学生信息和最新动态",
"schema": {
"$ref": "#/definitions/api_we.GetCardUserAndTrendRes"
"$ref": "#/definitions/api_we.getCardUserAndTrendRes"
}
}
}
......@@ -692,7 +675,7 @@
"tags": [
"家长微信"
],
"summary": "修改亲情号的昵称(注:号码本身不可修改,只能删除和添加) [complete]",
"summary": "修改亲情号的昵称(注:号码本身不可修改,只能删除和添加,仅主家长有权限) [complete] 最新调整为仅主家长有权限",
"parameters": [
{
"type": "integer",
......@@ -735,7 +718,7 @@
"tags": [
"家长微信"
],
"summary": "添加亲情号 [complete]",
"summary": "添加亲情号(仅主家长有权限) [complete] 最新调整为仅主家长有权限",
"parameters": [
{
"type": "integer",
......@@ -776,7 +759,7 @@
"tags": [
"家长微信"
],
"summary": "删除亲情号 [complete]",
"summary": "删除亲情号(仅主家长有权限) [complete] 最新调整为仅主家长有权限",
"parameters": [
{
"type": "integer",
......@@ -802,13 +785,84 @@
}
}
},
"/we/familynumtest/{id}": {
"post": {
"security": [
{
"ApiKeyAuth": []
}
],
"description": "家长绑定亲情号接口",
"consumes": [
"application/json"
],
"produces": [
"application/json"
],
"tags": [
"家长微信"
],
"summary": "添加亲情号(仅主家长有权限) [complete] 用于测试卡的添加,当前测试卡\"89861120040280843640\"",
"parameters": [
{
"type": "integer",
"description": "学生ID",
"name": "id",
"in": "path",
"required": true
},
{
"description": "亲情号内容",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/model.CacheFamilyOnePerson"
}
}
],
"responses": {
"0": {
"description": ""
}
}
}
},
"/we/login/{code}": {
"post": {
"description": "微信code传至后台,后台返回token,token有效时长:48小时",
"tags": [
"家长微信"
],
"summary": "登录 [complete]",
"summary": "登录(真实code) [complete]",
"parameters": [
{
"description": "登录信息",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_we.weLoginReq"
}
}
],
"responses": {
"0": {
"description": "",
"schema": {
"$ref": "#/definitions/api_we.weLoginRes"
}
}
}
}
},
"/we/logintest/{code}": {
"post": {
"description": "微信code传至后台,后台返回token,token有效时长:48小时",
"tags": [
"家长微信"
],
"summary": "登录(测试的假code) [complete]",
"parameters": [
{
"description": "登录信息",
......@@ -1001,7 +1055,10 @@
"0": {
"description": "",
"schema": {
"$ref": "#/definitions/api_we.weUserListStruct"
"type": "array",
"items": {
"$ref": "#/definitions/api_we.weResUserInfoStruct"
}
}
}
}
......@@ -1040,6 +1097,72 @@
}
}
}
},
"/we/webindinfo": {
"post": {
"security": [
{
"ApiKeyAuth": []
}
],
"description": "上传用户授权获取到的微信头像昵称",
"produces": [
"application/json"
],
"tags": [
"家长微信"
],
"summary": "上传微信用户头像昵称 [complete]",
"parameters": [
{
"description": "头像昵称信息",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_we.wechatUserBindWeInfoStruct"
}
}
],
"responses": {
"0": {
"description": ""
}
}
}
},
"/we/webindphone": {
"post": {
"security": [
{
"ApiKeyAuth": []
}
],
"description": "上传用户授权获取到的微信手机号",
"produces": [
"application/json"
],
"tags": [
"家长微信"
],
"summary": "上传微信用户手机号 [complete]",
"parameters": [
{
"description": "手机号",
"name": "data",
"in": "body",
"required": true,
"schema": {
"$ref": "#/definitions/api_we.wechatUserBindWePhoneStruct"
}
}
],
"responses": {
"0": {
"description": ""
}
}
}
}
},
"definitions": {
......@@ -1073,116 +1196,17 @@
}
}
},
"api_we.BindCardUserRes": {
"api_server_ops.apiGetSystemRunParaStruct": {
"type": "object",
"properties": {
"area": {
"description": "区域名字",
"type": "string",
"example": "温江实验中学"
},
"class": {
"description": "0无意义",
"goroutineNum": {
"type": "integer"
},
"grade": {
"description": "0无意义 \"1~9对应一年级~九年级,10~12对应高一~高三\"",
"numCPU": {
"type": "integer"
},
"id": {
"description": "学生ID",
"phoneTcpSocketNum": {
"type": "integer"
},
"master": {
"description": "true:本来就是主家长,false:已成功绑定成副家长",
"type": "boolean",
"example": false
},
"name": {
"type": "string"
},
"service": {
"description": "对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)",
"type": "array",
"items": {
"type": "integer"
},
"example": [
1,
2,
2,
0,
0,
0
]
},
"sex": {
"description": "0无意义 1女 2男",
"type": "integer"
},
"stuNum": {
"description": "\"\"无意义",
"type": "string"
},
"trend": {
"type": "array",
"items": {
"$ref": "#/definitions/model.CacheCardUserTrendStruct"
}
}
}
},
"api_we.GetCardUserAndTrendRes": {
"type": "object",
"properties": {
"area": {
"description": "区域名字",
"type": "string",
"example": "温江实验中学"
},
"class": {
"description": "0无意义",
"type": "integer"
},
"grade": {
"description": "0无意义 \"1~9对应一年级~九年级,10~12对应高一~高三\"",
"type": "integer"
},
"id": {
"description": "学生ID",
"type": "integer"
},
"name": {
"type": "string"
},
"service": {
"description": "对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)",
"type": "array",
"items": {
"type": "integer"
},
"example": [
1,
2,
2,
0,
0,
0
]
},
"sex": {
"description": "0无意义 1女 2男",
"type": "integer"
},
"stuNum": {
"description": "\"\"无意义",
"type": "string"
},
"trend": {
"type": "array",
"items": {
"$ref": "#/definitions/model.CacheCardUserTrendStruct"
}
}
}
},
......@@ -1206,6 +1230,10 @@
"description": "学生ID",
"type": "integer"
},
"master": {
"description": "是否为主家长",
"type": "boolean"
},
"name": {
"type": "string"
},
......@@ -1234,39 +1262,6 @@
}
}
},
"api_we.WeResUserInfoStruct": {
"type": "object",
"properties": {
"area": {
"description": "区域名字",
"type": "string",
"example": "温江实验中学"
},
"class": {
"description": "0无意义",
"type": "integer"
},
"grade": {
"description": "0无意义 \"1~9对应一年级~九年级,10~12对应高一~高三\"",
"type": "integer"
},
"id": {
"description": "学生ID",
"type": "integer"
},
"name": {
"type": "string"
},
"sex": {
"description": "0无意义 1女 2男",
"type": "integer"
},
"stuNum": {
"description": "\"\"无意义",
"type": "string"
}
}
},
"api_we.apiCardBindStruct": {
"type": "object",
"properties": {
......@@ -1324,6 +1319,64 @@
}
}
},
"api_we.getCardUserAndTrendRes": {
"type": "object",
"properties": {
"area": {
"description": "区域名字",
"type": "string",
"example": "温江实验中学"
},
"class": {
"description": "0无意义",
"type": "integer"
},
"grade": {
"description": "0无意义 \"1~9对应一年级~九年级,10~12对应高一~高三\"",
"type": "integer"
},
"id": {
"description": "学生ID",
"type": "integer"
},
"master": {
"description": "是否为主家长",
"type": "boolean"
},
"name": {
"type": "string"
},
"service": {
"description": "对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)",
"type": "array",
"items": {
"type": "integer"
},
"example": [
1,
2,
2,
0,
0,
0
]
},
"sex": {
"description": "0无意义 1女 2男",
"type": "integer"
},
"stuNum": {
"description": "\"\"无意义",
"type": "string"
},
"trend": {
"type": "array",
"items": {
"$ref": "#/definitions/model.CacheCardUserTrendStruct"
}
}
}
},
"api_we.getPhoneCardStatusRes": {
"type": "object",
"properties": {
......@@ -1397,19 +1450,11 @@
"api_we.weLoginReq": {
"type": "object",
"properties": {
"avatarurl": {
"description": "选填,用户头像URL",
"type": "string"
},
"code": {
"description": "必填,登录要用的微信code",
"type": "string",
"example": "codeTest1"
},
"nickname": {
"description": "选填,用户昵称",
"type": "string"
},
"token": {
"description": "选填,如果有旧的token,也带过来",
"type": "string"
......@@ -1424,62 +1469,79 @@
"type": "integer"
},
"token": {
"description": "weUserListStruct\nWePhone bool `json:\"wePhone\"` // 是否已获取到微信电话\nWeInfo bool `json:\"weInfo\"` // 是否已获取到微信用户信息",
"type": "string"
},
"weInfo": {
"description": "是否已获取到微信用户信息,为false则需要获取",
"type": "boolean"
},
"wePhone": {
"description": "weUserListStruct",
"type": "boolean"
}
}
},
"api_we.weUserListStruct": {
"api_we.weResUserInfoStruct": {
"type": "object",
"properties": {
"area": {
"description": "区域名字",
"type": "string",
"example": "温江实验中学"
},
"class": {
"description": "0无意义",
"type": "integer"
},
"grade": {
"description": "0无意义 \"1~9对应一年级~九年级,10~12对应高一~高三\"",
"type": "integer"
},
"id": {
"description": "学生ID",
"type": "integer"
},
"master": {
"description": "自己创建的学生列表(主家长)",
"type": "array",
"items": {
"$ref": "#/definitions/api_we.WeResUserInfoStruct"
}
"description": "是否为主家长",
"type": "boolean"
},
"slave": {
"description": "添加的学生列表(副家长)",
"type": "array",
"items": {
"$ref": "#/definitions/api_we.WeResUserInfoStruct"
}
"name": {
"type": "string"
},
"sex": {
"description": "0无意义 1女 2男",
"type": "integer"
},
"stuNum": {
"description": "\"\"无意义",
"type": "string"
}
}
},
"dbcurd.TableBaseArea": {
"api_we.wechatUserBindWeInfoStruct": {
"type": "object",
"properties": {
"county_id": {
"description": "必填,所属区县ID",
"type": "integer",
"example": 2725
},
"creator_id": {
"description": "测试用,以后不传这个字段",
"type": "integer",
"example": 1
},
"latitude": {
"description": "必填,纬度",
"type": "integer",
"example": 30000000
"avatarurl": {
"description": "用户头像URL",
"type": "string"
},
"longitude": {
"description": "必填,经度",
"type": "integer",
"example": 103000000
"nickname": {
"description": "用户昵称",
"type": "string"
}
}
},
"api_we.wechatUserBindWePhoneStruct": {
"type": "object",
"properties": {
"code": {
"type": "string"
},
"name": {
"description": "必填,名字",
"type": "string",
"example": "多彩温江校区"
"encryptedData": {
"type": "string"
},
"status": {
"description": "必填,是否测试校区,0预留 1正示 2测试校区",
"type": "integer",
"example": 1
"iv": {
"type": "string"
}
}
},
......
......@@ -21,89 +21,14 @@ definitions:
example: 海科学校
type: string
type: object
api_we.BindCardUserRes:
api_server_ops.apiGetSystemRunParaStruct:
properties:
area:
description: 区域名字
example: 温江实验中学
type: string
class:
description: 0无意义
type: integer
grade:
description: 0无意义 "1~9对应一年级~九年级,10~12对应高一~高三"
goroutineNum:
type: integer
id:
description: 学生ID
numCPU:
type: integer
master:
description: true:本来就是主家长,false:已成功绑定成副家长
example: false
type: boolean
name:
type: string
service:
description: 对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)
example:
- 1
- 2
- 2
- 0
- 0
- 0
items:
type: integer
type: array
sex:
description: 0无意义 1女 2男
phoneTcpSocketNum:
type: integer
stuNum:
description: '""无意义'
type: string
trend:
items:
$ref: '#/definitions/model.CacheCardUserTrendStruct'
type: array
type: object
api_we.GetCardUserAndTrendRes:
properties:
area:
description: 区域名字
example: 温江实验中学
type: string
class:
description: 0无意义
type: integer
grade:
description: 0无意义 "1~9对应一年级~九年级,10~12对应高一~高三"
type: integer
id:
description: 学生ID
type: integer
name:
type: string
service:
description: 对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)
example:
- 1
- 2
- 2
- 0
- 0
- 0
items:
type: integer
type: array
sex:
description: 0无意义 1女 2男
type: integer
stuNum:
description: '""无意义'
type: string
trend:
items:
$ref: '#/definitions/model.CacheCardUserTrendStruct'
type: array
type: object
api_we.GetCardUserInfoRes:
properties:
......@@ -120,6 +45,9 @@ definitions:
id:
description: 学生ID
type: integer
master:
description: 是否为主家长
type: boolean
name:
type: string
service:
......@@ -141,30 +69,6 @@ definitions:
description: '""无意义'
type: string
type: object
api_we.WeResUserInfoStruct:
properties:
area:
description: 区域名字
example: 温江实验中学
type: string
class:
description: 0无意义
type: integer
grade:
description: 0无意义 "1~9对应一年级~九年级,10~12对应高一~高三"
type: integer
id:
description: 学生ID
type: integer
name:
type: string
sex:
description: 0无意义 1女 2男
type: integer
stuNum:
description: '""无意义'
type: string
type: object
api_we.apiCardBindStruct:
properties:
code:
......@@ -205,6 +109,49 @@ definitions:
description: 必填,副家长的id
type: integer
type: object
api_we.getCardUserAndTrendRes:
properties:
area:
description: 区域名字
example: 温江实验中学
type: string
class:
description: 0无意义
type: integer
grade:
description: 0无意义 "1~9对应一年级~九年级,10~12对应高一~高三"
type: integer
id:
description: 学生ID
type: integer
master:
description: 是否为主家长
type: boolean
name:
type: string
service:
description: 对应6个数字对应公话、定位、饮水、卡消费、洗浴、洗衣机图标(0不显示,1正常,2显示但提示校区暂未开通该服务)
example:
- 1
- 2
- 2
- 0
- 0
- 0
items:
type: integer
type: array
sex:
description: 0无意义 1女 2男
type: integer
stuNum:
description: '""无意义'
type: string
trend:
items:
$ref: '#/definitions/model.CacheCardUserTrendStruct'
type: array
type: object
api_we.getPhoneCardStatusRes:
properties:
deleteable:
......@@ -257,16 +204,10 @@ definitions:
type: object
api_we.weLoginReq:
properties:
avatarurl:
description: 选填,用户头像URL
type: string
code:
description: 必填,登录要用的微信code
example: codeTest1
type: string
nickname:
description: 选填,用户昵称
type: string
token:
description: 选填,如果有旧的token,也带过来
type: string
......@@ -277,51 +218,58 @@ definitions:
description: 到期时间,10位时间戳
type: integer
token:
description: |-
weUserListStruct
WePhone bool `json:"wePhone"` // 是否已获取到微信电话
WeInfo bool `json:"weInfo"` // 是否已获取到微信用户信息
type: string
weInfo:
description: 是否已获取到微信用户信息,为false则需要获取
type: boolean
wePhone:
description: weUserListStruct
type: boolean
type: object
api_we.weUserListStruct:
properties:
master:
description: 自己创建的学生列表(主家长)
items:
$ref: '#/definitions/api_we.WeResUserInfoStruct'
type: array
slave:
description: 添加的学生列表(副家长)
items:
$ref: '#/definitions/api_we.WeResUserInfoStruct'
type: array
type: object
dbcurd.TableBaseArea:
api_we.weResUserInfoStruct:
properties:
county_id:
description: 必填,所属区县ID
example: 2725
type: integer
creator_id:
description: 测试用,以后不传这个字段
example: 1
area:
description: 区域名字
example: 温江实验中学
type: string
class:
description: 0无意义
type: integer
latitude:
description: 必填,纬度
example: 30000000
grade:
description: 0无意义 "1~9对应一年级~九年级,10~12对应高一~高三"
type: integer
longitude:
description: 必填,经度
example: 103000000
id:
description: 学生ID
type: integer
master:
description: 是否为主家长
type: boolean
name:
description: 必填,名字
example: 多彩温江校区
type: string
status:
description: 必填,是否测试校区,0预留 1正示 2测试校区
example: 1
sex:
description: 0无意义 1女 2男
type: integer
stuNum:
description: '""无意义'
type: string
type: object
api_we.wechatUserBindWeInfoStruct:
properties:
avatarurl:
description: 用户头像URL
type: string
nickname:
description: 用户昵称
type: string
type: object
api_we.wechatUserBindWePhoneStruct:
properties:
code:
type: string
encryptedData:
type: string
iv:
type: string
type: object
model.CacheBDistrictStruct:
properties:
......@@ -402,34 +350,13 @@ definitions:
type: object
info:
contact: {}
description: 用于家长端微信小程序及web端管理后台
description: |-
2021-10-31-V0.0.2 添加、删除亲情号以及修改亲情号昵称调整为仅主家长有权限,免得副家长随便改浪费移动的次数
2021-11-01 1. 登录接口不再上传昵称头像 2. 增加上传微信昵称头像接口和上传微信绑定手机号接口
2021-11-01 15:30 1. 学生列表接口返回内容小调整 2. 学生信息返回内容增加master字段
title: 多彩中小学一卡通系统
version: V0.0.0.1
version: V0.0.2
paths:
/ad/area:
post:
consumes:
- application/json
description: 目前仅用于填充数据,暂未做权限校验
parameters:
- description: 学校信息
in: body
name: data
required: true
schema:
$ref: '#/definitions/dbcurd.TableBaseArea'
produces:
- application/json
responses:
"0":
description: ""
schema:
type: integer
security:
- ApiKeyAuth: []
summary: 创建一个学校
tags:
- 管理后台
/base/city/{provinceID}:
get:
description: 获取带首字母的城市列表
......@@ -537,6 +464,19 @@ paths:
summary: 获取全国省份列表 [complete]
tags:
- 公用接口
/server/goroutinenum:
get:
description: 返回当前程序运行状态
responses:
"0":
description: 程序运行状态
schema:
$ref: '#/definitions/api_server_ops.apiGetSystemRunParaStruct'
security:
- ApiKeyAuth: []
summary: 获取当前程序运行状态
tags:
- 运维
/we/bindcarduser/{id}:
delete:
description: 传学生ID至后台,后台返回成功失败
......@@ -593,7 +533,7 @@ paths:
"0":
description: 学生信息
schema:
$ref: '#/definitions/api_we.BindCardUserRes'
$ref: '#/definitions/api_we.getCardUserAndTrendRes'
"30":
description: 邀请码无效
"31":
......@@ -820,7 +760,7 @@ paths:
"0":
description: 学生信息和最新动态
schema:
$ref: '#/definitions/api_we.GetCardUserAndTrendRes'
$ref: '#/definitions/api_we.getCardUserAndTrendRes'
security:
- ApiKeyAuth: []
summary: 获取单个学生信息和最新动态[complete]
......@@ -850,7 +790,7 @@ paths:
description: ""
security:
- ApiKeyAuth: []
summary: 修改亲情号的昵称(注:号码本身不可修改,只能删除和添加) [complete]
summary: 修改亲情号的昵称(注:号码本身不可修改,只能删除和添加,仅主家长有权限) [complete] 最新调整为仅主家长有权限
tags:
- 家长微信
/we/familynum/{id}:
......@@ -877,9 +817,36 @@ paths:
description: ""
security:
- ApiKeyAuth: []
summary: 删除亲情号 [complete]
summary: 删除亲情号(仅主家长有权限) [complete] 最新调整为仅主家长有权限
tags:
- 家长微信
post:
consumes:
- application/json
description: 家长绑定亲情号接口
parameters:
- description: 学生ID
in: path
name: id
required: true
type: integer
- description: 亲情号内容
in: body
name: data
required: true
schema:
$ref: '#/definitions/model.CacheFamilyOnePerson'
produces:
- application/json
responses:
"0":
description: ""
security:
- ApiKeyAuth: []
summary: 添加亲情号(仅主家长有权限) [complete] 最新调整为仅主家长有权限
tags:
- 家长微信
/we/familynumtest/{id}:
post:
consumes:
- application/json
......@@ -903,7 +870,7 @@ paths:
description: ""
security:
- ApiKeyAuth: []
summary: 添加亲情号 [complete]
summary: 添加亲情号(仅主家长有权限) [complete] 用于测试卡的添加,当前测试卡"89861120040280843640"
tags:
- 家长微信
/we/login/{code}:
......@@ -921,7 +888,25 @@ paths:
description: ""
schema:
$ref: '#/definitions/api_we.weLoginRes'
summary: 登录 [complete]
summary: 登录(真实code) [complete]
tags:
- 家长微信
/we/logintest/{code}:
post:
description: 微信code传至后台,后台返回token,token有效时长:48小时
parameters:
- description: 登录信息
in: body
name: data
required: true
schema:
$ref: '#/definitions/api_we.weLoginReq'
responses:
"0":
description: ""
schema:
$ref: '#/definitions/api_we.weLoginRes'
summary: 登录(测试的假code) [complete]
tags:
- 家长微信
/we/phonecardstatus/{id}:
......@@ -1028,7 +1013,9 @@ paths:
"0":
description: ""
schema:
$ref: '#/definitions/api_we.weUserListStruct'
items:
$ref: '#/definitions/api_we.weResUserInfoStruct'
type: array
security:
- ApiKeyAuth: []
summary: 获取学生列表 [complete]
......@@ -1055,6 +1042,46 @@ paths:
summary: 微信学生首页,获取近20条用户最新动态 [complete]
tags:
- 家长微信
/we/webindinfo:
post:
description: 上传用户授权获取到的微信头像昵称
parameters:
- description: 头像昵称信息
in: body
name: data
required: true
schema:
$ref: '#/definitions/api_we.wechatUserBindWeInfoStruct'
produces:
- application/json
responses:
"0":
description: ""
security:
- ApiKeyAuth: []
summary: 上传微信用户头像昵称 [complete]
tags:
- 家长微信
/we/webindphone:
post:
description: 上传用户授权获取到的微信手机号
parameters:
- description: 手机号
in: body
name: data
required: true
schema:
$ref: '#/definitions/api_we.wechatUserBindWePhoneStruct'
produces:
- application/json
responses:
"0":
description: ""
security:
- ApiKeyAuth: []
summary: 上传微信用户手机号 [complete]
tags:
- 家长微信
securityDefinitions:
ApiKeyAuth:
in: header
......
{"level":"INFO","ts":"2021-10-29 15:37:55.856","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/index.html","DataSize":3511,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 15:37:56.121","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui.css","DataSize":143669,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 15:37:56.125","msg":"","Status":200,"SpendMS":3,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui-bundle.js","DataSize":1091405,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 15:37:56.126","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui-standalone-preset.js","DataSize":337216,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 15:37:56.607","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/doc.json","DataSize":54044,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 15:38:03.451","msg":"","Status":200,"SpendMS":45,"Ip":"127.0.0.1","Method":"POST","Path":"/we/login/%7Bcode%7D","DataSize":323,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:17:01.053","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/index.html","DataSize":3511,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:17:01.096","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui.css","DataSize":143669,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:17:01.100","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui-standalone-preset.js","DataSize":337216,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:17:01.100","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui-bundle.js","DataSize":1091405,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:17:01.597","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/doc.json","DataSize":53800,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:17:12.071","msg":"","Status":200,"SpendMS":86,"Ip":"127.0.0.1","Method":"POST","Path":"/we/login/%7Bcode%7D","DataSize":78,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:56:30.046","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/index.html","DataSize":3511,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:56:30.067","msg":"","Status":200,"SpendMS":2,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui.css","DataSize":143669,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:56:30.072","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui-standalone-preset.js","DataSize":337216,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:56:30.074","msg":"","Status":200,"SpendMS":4,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui-bundle.js","DataSize":1091405,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:56:30.564","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/doc.json","DataSize":55671,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:56:50.652","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"POST","Path":"/we/login/%7Bcode%7D","DataSize":78,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:58:03.881","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"GET","Path":"/we/sharestring/5?time=60","DataSize":36,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 19:58:12.328","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/we/previewcarduser/ThpVinmAdJ62fk_9","DataSize":155,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:01:08.621","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/index.html","DataSize":3511,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:01:08.642","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui.css","DataSize":143669,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:01:08.646","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui-standalone-preset.js","DataSize":337216,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:01:08.647","msg":"","Status":200,"SpendMS":3,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui-bundle.js","DataSize":1091405,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:01:09.043","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/doc.json","DataSize":55671,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:01:59.718","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"POST","Path":"/we/login/%7Bcode%7D","DataSize":78,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:02:13.859","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/we/sharestring/5?time=60","DataSize":36,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:02:28.089","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/we/previewcarduser/-UZ6saCdm8XdwwjW","DataSize":76,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:05:28.835","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/we/previewcarduser/-UZ6saCdm8XdwwjW","DataSize":79,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:05:31.265","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/we/previewcarduser/-UZ6saCdm8XdwwjW","DataSize":79,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:08:50.261","msg":"","Status":200,"SpendMS":167719,"Ip":"127.0.0.1","Method":"GET","Path":"/we/previewcarduser/-UZ6saCdm8XdwwjW","DataSize":79,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:10:17.340","msg":"","Status":200,"SpendMS":33486,"Ip":"127.0.0.1","Method":"GET","Path":"/we/sharestring/5?time=60","DataSize":36,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:10:25.426","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/we/sharestring/5?time=60","DataSize":36,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:10:44.243","msg":"","Status":200,"SpendMS":5356,"Ip":"127.0.0.1","Method":"GET","Path":"/we/previewcarduser/q_tTeskixO2Kmmat","DataSize":79,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:11:55.737","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/we/previewcarduser/q_tTeskixO2Kmmat","DataSize":79,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:11:58.832","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/we/previewcarduser/q_tTeskixO2Kmmat","DataSize":79,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:12:44.724","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/we/previewcarduser/q_tTeskixO2Kmmat","DataSize":66,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:18:36.165","msg":"","Status":200,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/index.html","DataSize":3511,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:18:36.186","msg":"","Status":200,"SpendMS":1,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui.css","DataSize":143669,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:18:36.190","msg":"","Status":200,"SpendMS":2,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui-standalone-preset.js","DataSize":337216,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:18:36.191","msg":"","Status":200,"SpendMS":4,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/swagger-ui-bundle.js","DataSize":1091405,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"INFO","ts":"2021-10-29 20:18:36.606","msg":"","Status":200,"SpendMS":2,"Ip":"127.0.0.1","Method":"GET","Path":"/swagger/doc.json","DataSize":55671,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"WARN","ts":"2021-10-29 15:38:21.399","msg":"","Status":404,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/","DataSize":0,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
{"level":"WARN","ts":"2021-10-29 15:38:22.300","msg":"","Status":404,"SpendMS":0,"Ip":"127.0.0.1","Method":"GET","Path":"/favicon.ico","DataSize":0,"Agent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3875.400 QQBrowser/10.8.4492.400"}
package logger
import (
config3 "dc_golang_server_1/util/config"
"github.com/gin-gonic/gin"
"github.com/natefinch/lumberjack"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"time"
)
var Log *zap.Logger
var logGin *zap.Logger
var LogHttpClient *zap.Logger
func Init() {
config := zapcore.EncoderConfig{
MessageKey: "msg", //结构化(json)输出:msg的key
LevelKey: "level", //结构化(json)输出:日志级别的key(INFO,WARN,ERROR等)
TimeKey: "ts", //结构化(json)输出:时间的key(INFO,WARN,ERROR等)
CallerKey: "file", //结构化(json)输出:打印日志的文件对应的Key
EncodeLevel: zapcore.CapitalLevelEncoder, //将日志级别转换成大写(INFO,WARN,ERROR等)
EncodeCaller: zapcore.ShortCallerEncoder, //采用短文件路径编码输出(test/main.go:14 )
EncodeTime: func(t time.Time, enc zapcore.PrimitiveArrayEncoder) {
enc.AppendString(t.Format("2006-01-02 15:04:05.000"))
}, //输出的时间格式
//EncodeDuration: func(d time.Duration, enc zapcore.PrimitiveArrayEncoder) {
// enc.AppendInt64(int64(d) / 1000000)
//},//
}
//debug info
infoLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl < zapcore.WarnLevel && lvl >= config3.LogLevel
})
//warn
warnLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl == zapcore.WarnLevel && lvl >= config3.LogLevel
})
//error DPanic Panci Fatal
errorLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl > zapcore.WarnLevel && lvl >= config3.LogLevel
})
infoWriter := &lumberjack.Logger{
Filename: config3.LogPath + "info.log",
MaxSize: config3.LogFileMaxSize, //最大M数,超过则切割
MaxBackups: config3.LogInfoMaxFileNum, //最大文件保留数,超过就删除最老的日志文件
MaxAge: config3.LogInfoMaxFileDay, //保存30天
Compress: false, //是否压缩
}
warnWriter := &lumberjack.Logger{
Filename: config3.LogPath + "warn.log",
MaxSize: config3.LogFileMaxSize, //最大M数,超过则切割
MaxBackups: config3.LogWarnMaxFileNum, //最大文件保留数,超过就删除最老的日志文件
MaxAge: config3.LogWarnMaxFileDay, //保存30天
Compress: false, //是否压缩
}
errorWriter := &lumberjack.Logger{
Filename: config3.LogPath + "error.log",
MaxSize: config3.LogFileMaxSize, //最大M数,超过则切割
MaxBackups: config3.LogErrorMaxFileNum, //最大文件保留数,超过就删除最老的日志文件
MaxAge: config3.LogErrorMaxFileDay, //保存30天
Compress: false, //是否压缩
}
core := zapcore.NewTee(
zapcore.NewCore(zapcore.NewJSONEncoder(config), zapcore.AddSync(infoWriter), infoLevel), // zapcore.NewConsoleEncoder(encoder)
zapcore.NewCore(zapcore.NewJSONEncoder(config), zapcore.AddSync(warnWriter), warnLevel), //
zapcore.NewCore(zapcore.NewJSONEncoder(config), zapcore.AddSync(errorWriter), errorLevel), //
//zapcore.NewCore(zapcore.NewJSONEncoder(encoder), zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout)), logLevel),//同时将日志输出到控制台,NewJSONEncoder 是结构化输出
)
Log = zap.New(core, zap.AddStacktrace(zap.ErrorLevel))
infoWriter = &lumberjack.Logger{
Filename: config3.LogPath + "infoGin.log",
MaxSize: config3.LogFileMaxSize, //最大M数,超过则切割
MaxBackups: config3.LogInfoMaxFileNum, //最大文件保留数,超过就删除最老的日志文件
MaxAge: config3.LogInfoMaxFileDay, //保存30天
Compress: false, //是否压缩
}
warnWriter = &lumberjack.Logger{
Filename: config3.LogPath + "warnGin.log",
MaxSize: config3.LogFileMaxSize, //最大M数,超过则切割
MaxBackups: config3.LogWarnMaxFileNum, //最大文件保留数,超过就删除最老的日志文件
MaxAge: config3.LogWarnMaxFileDay, //保存30天
Compress: false, //是否压缩
}
errorWriter = &lumberjack.Logger{
Filename: config3.LogPath + "errorGin.log",
MaxSize: config3.LogFileMaxSize, //最大M数,超过则切割
MaxBackups: config3.LogErrorMaxFileNum, //最大文件保留数,超过就删除最老的日志文件
MaxAge: config3.LogErrorMaxFileDay, //保存30天
Compress: false, //是否压缩
}
core = zapcore.NewTee(
zapcore.NewCore(zapcore.NewJSONEncoder(config), zapcore.AddSync(infoWriter), infoLevel), // zapcore.NewConsoleEncoder(encoder)
zapcore.NewCore(zapcore.NewJSONEncoder(config), zapcore.AddSync(warnWriter), warnLevel), //
zapcore.NewCore(zapcore.NewJSONEncoder(config), zapcore.AddSync(errorWriter), errorLevel), //
//zapcore.NewCore(zapcore.NewJSONEncoder(encoder), zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout)), logLevel),//同时将日志输出到控制台,NewJSONEncoder 是结构化输出
)
logGin = zap.New(core, zap.AddStacktrace(zap.ErrorLevel))
infoWriter = &lumberjack.Logger{
Filename: config3.LogPath + "infoClient.log",
MaxSize: config3.LogFileMaxSize, //最大M数,超过则切割
MaxBackups: config3.LogInfoMaxFileNum, //最大文件保留数,超过就删除最老的日志文件
MaxAge: config3.LogInfoMaxFileDay, //保存30天
Compress: false, //是否压缩
}
warnWriter = &lumberjack.Logger{
Filename: config3.LogPath + "warnClient.log",
MaxSize: config3.LogFileMaxSize, //最大M数,超过则切割
MaxBackups: config3.LogWarnMaxFileNum, //最大文件保留数,超过就删除最老的日志文件
MaxAge: config3.LogWarnMaxFileDay, //保存30天
Compress: false, //是否压缩
}
errorWriter = &lumberjack.Logger{
Filename: config3.LogPath + "errorClient.log",
MaxSize: config3.LogFileMaxSize, //最大M数,超过则切割
MaxBackups: config3.LogErrorMaxFileNum, //最大文件保留数,超过就删除最老的日志文件
MaxAge: config3.LogErrorMaxFileDay, //保存30天
Compress: false, //是否压缩
}
core = zapcore.NewTee(
zapcore.NewCore(zapcore.NewJSONEncoder(config), zapcore.AddSync(infoWriter), infoLevel), // zapcore.NewConsoleEncoder(encoder)
zapcore.NewCore(zapcore.NewJSONEncoder(config), zapcore.AddSync(warnWriter), warnLevel), //
zapcore.NewCore(zapcore.NewJSONEncoder(config), zapcore.AddSync(errorWriter), errorLevel), //
//zapcore.NewCore(zapcore.NewJSONEncoder(encoder), zapcore.NewMultiWriteSyncer(zapcore.AddSync(os.Stdout)), logLevel),//同时将日志输出到控制台,NewJSONEncoder 是结构化输出
)
LogHttpClient = zap.New(core, zap.AddStacktrace(zap.ErrorLevel))
}
func HttpGinLog() gin.HandlerFunc { //logger *log.Log
return func(c *gin.Context) {
startTime := time.Now().UnixMilli()
c.Next()
spendTime := time.Now().UnixMilli() - startTime
// hostName, err := os.Hostname()
//if err != nil {
// hostName = "unknown"
//}
statusCode := c.Writer.Status()
clientIp := c.ClientIP()
userAgent := c.Request.UserAgent()
dataSize := c.Writer.Size()
if dataSize < 0 {
dataSize = 0
}
method := c.Request.Method
path := c.Request.RequestURI
//c.Request.Body.Read()
//body := c.Request.Body
//para := c.Params
//entry := Log.WithFields(log.Fields{
// "HostName": hostName,
// "Status": statusCode,
// "SpendNanoS": spendTime,
// "Ip": clientIp,
// "Method": method,
// "Path": path,
// "DataSize": dataSize,
// "Agent": userAgent,
//})
if len(c.Errors) > 0 {
//entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
logGin.Error(c.Errors.ByType(gin.ErrorTypePrivate).String(),
// zap.String("HostName", hostName),
zap.Int("Status", statusCode),
zap.Int64("SpendMS", spendTime),
zap.String("Ip", clientIp),
zap.String("Method", method),
zap.String("Path", path),
zap.Int("DataSize", dataSize),
zap.String("Agent", userAgent))
}
if statusCode >= 500 {
logGin.Error("",
// zap.String("HostName", hostName),
zap.Int("Status", statusCode),
zap.Int64("SpendMS", spendTime),
zap.String("Ip", clientIp),
zap.String("Method", method),
zap.String("Path", path),
zap.Int("DataSize", dataSize),
zap.String("Agent", userAgent))
} else if statusCode >= 400 {
logGin.Warn("",
// zap.String("HostName", hostName),
zap.Int("Status", statusCode),
zap.Int64("SpendMS", spendTime),
zap.String("Ip", clientIp),
zap.String("Method", method),
zap.String("Path", path),
zap.Int("DataSize", dataSize),
zap.String("Agent", userAgent))
} else {
logGin.Info("",
// zap.String("HostName", hostName),
zap.Int("Status", statusCode),
zap.Int64("SpendMS", spendTime),
zap.String("Ip", clientIp),
zap.String("Method", method),
zap.String("Path", path),
zap.Int("DataSize", dataSize),
zap.String("Agent", userAgent))
}
}
}
//import (
// "github.com/gin-gonic/gin"
// rotatelogs "github.com/lestrrat-go/file-rotatelogs"
// "github.com/rifflock/lfshook"
// log "github.com/sirupsen/logrus"
// "jeff_workstation_1/util"
// "os"
// "time"
//)
//
//func InitLogger(filePath string){
//
// // log.SetOutput(colorable.NewColorableStdout())
//
// // log.SetOutput(f)
// log.SetLevel(util.LogLevel)
//
// TraceLogWriter,_ := rotatelogs.New(
// filePath+"Trace_%Y%m%d%H.log",
// rotatelogs.WithMaxAge(util.LogTraceWithMaxAge),
// rotatelogs.WithRotationTime(util.LogTraceWithRotationTime),
// //rotatelogs.WithLinkName(linkName),
// )
// DebugLogWriter,_ := rotatelogs.New(
// filePath+"Debug_%Y%m%d%H.log",
// rotatelogs.WithMaxAge(util.LogDebugWithMaxAge),
// rotatelogs.WithRotationTime(util.LogDebugWithRotationTime),
// //rotatelogs.WithLinkName(linkName),
// )
// infoLogWriter,_ := rotatelogs.New(
// filePath+"Info_%Y%m%d%H.log",
// rotatelogs.WithMaxAge(util.LogInfoWithMaxAge),
// rotatelogs.WithRotationTime(util.LogInfoWithRotationTime),
// //rotatelogs.WithLinkName("tcp_info.log"),
// )
// WarnLogWriter,_ := rotatelogs.New(
// filePath+"Warn_%Y%m%d%H.log",
// rotatelogs.WithMaxAge(util.LogWarnWithMaxAge),
// rotatelogs.WithRotationTime(util.LogWarnWithRotationTime),
// //rotatelogs.WithLinkName("tcp_warn.log"),
// )
// ErrorLogWriter,_ := rotatelogs.New(
// filePath+"Error_%Y%m%d%H.log",
// rotatelogs.WithMaxAge(util.LogErrorWithMaxAge),
// rotatelogs.WithRotationTime(util.LogErrorWithRotationTime),
// //rotatelogs.WithLinkName("tcp_error.log"),
// )
//
// writeMap := lfshook.WriterMap{
// log.TraceLevel: TraceLogWriter,
// log.DebugLevel: DebugLogWriter,
// log.InfoLevel: infoLogWriter,
// log.WarnLevel: WarnLogWriter,
// log.ErrorLevel: ErrorLogWriter,
// log.PanicLevel: ErrorLogWriter,
// log.FatalLevel: ErrorLogWriter,
// }
// hook := lfshook.NewHook(writeMap,&log.JSONFormatter{
// TimestampFormat: "2006-01-02 15:04:05.000000",
// })
//
// log.AddHook(hook)
// return
//}
//
//func HttpGinLog() gin.HandlerFunc{ //logger *log.Log
// return func(c *gin.Context) {
// startTime := time.Now().UnixNano()
// c.Next()
// //stopTime := time.Since(startTime)
// //spendTime := stopTime.Nanoseconds()/1000000///fmt.Sprintf("%d ms", (stopTime.Nanoseconds()+500000)/1000000)
// spendTime := time.Now().UnixNano() - startTime
// hostName, err := os.Hostname()
// if err != nil {
// hostName = "unknown"
// }
// statusCode := c.Writer.Status()
// clientIp := c.ClientIP()
// userAgent := c.Request.UserAgent()
// dataSize := c.Writer.Size()
// if dataSize < 0 {
// dataSize = 0
// }
// method := c.Request.Method
// path := c.Request.RequestURI
//
// //c.Request.Body.Read()
// //body := c.Request.Body
// //para := c.Params
//
// entry := log.WithFields(log.Fields{
// "HostName": hostName,
// "Status": statusCode,
// "SpendNanoS": spendTime,
// "Ip": clientIp,
// "Method": method,
// "Path": path,
// "DataSize": dataSize,
// "Agent": userAgent,
// })
//
// if len(c.Errors) > 0 {
// entry.Error(c.Errors.ByType(gin.ErrorTypePrivate).String())
// }
// if statusCode >= 500 {
// entry.Error()
// } else if statusCode >= 400 {
// entry.Warn()
// } else {
// entry.Info()
// }
// }
//}
......@@ -6,7 +6,7 @@ import (
"dc_golang_server_1/data_db_cache/dbcurd"
"dc_golang_server_1/devproduct/dcphone20"
"dc_golang_server_1/logger"
config2 "dc_golang_server_1/util/config"
"dc_golang_server_1/util/setting"
"fmt"
"os"
"os/signal"
......@@ -16,17 +16,21 @@ import (
)
// @title 多彩中小学一卡通系统
// @version V0.0.0.1
// @Description 用于家长端微信小程序及web端管理后台
// @version V0.0.2
// @Description 2021-10-31-V0.0.2 添加、删除亲情号以及修改亲情号昵称调整为仅主家长有权限,免得副家长随便改浪费移动的次数
// @Description 2021-11-01 1. 登录接口不再上传昵称头像 2. 增加上传微信昵称头像接口和上传微信绑定手机号接口
// @Description 2021-11-01 15:30 1. 学生列表接口返回内容小调整 2. 学生信息返回内容增加master字段
// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name token
// @BasePath /
func main() { //
fmt.Println(time.Now(), "system init")
runtime.GOMAXPROCS(runtime.NumCPU())
config2.Init()
fmt.Println("runtime.NumCPU()", runtime.NumCPU(), "runtime.GOMAXPROCS(runtime.NumCPU())", runtime.GOMAXPROCS(runtime.NumCPU()))
setting.Init()
logger.Init()
dbcurd.InitDb()
go func() {
osc := make(chan os.Signal, 1)
......@@ -37,9 +41,6 @@ func main() { //
os.Exit(1)
}()
dbcurd.InitDb()
// defer dbcurd.CloseDb()
cache.Init()
dcphone20.NewDCPhone20()
......@@ -47,3 +48,7 @@ func main() { //
router.InitRouter()
}
// 定时任务:
// 1. 每月最后一天晚上11点半开始,统一从移动系统删除亲情号,然后更新亲情号可修改次数,然后更新套餐分钟数。
// 2. 每晚校验缓存,同时更新用户登录次数和时间
package chinamobile
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"sync"
"time"
)
var lock sync.Mutex
var appId = "551AIOT2021090208593466876"
var password = "RMm9rMVXUT,S"
var token *Token
type Resp struct {
Status string `json:"status"`
Message string `json:"message"`
}
type Token struct {
Token string
ExpireTime int64 //到期时间戳。秒
}
type TokenResp struct {
Resp
Result []struct {
Token string `json:"token"`
TTL int `json:"ttl"`
} `json:"result"`
}
func main() {
//findPersonVoiceWhiteNumber("898608021221C0008054")
//queryGroupInfo()
//queryGroupByMember("898608021221C0008054")
//addMemberVoiceWhiteList("898608021221C0008054", "9911000019264204", "18111590295")
//queryMemberVoiceWhitelist("898608021221C0008054")
fmt.Println("------------------------------------------------------")
//addMemberVoiceWhiteList("898608021221C0008053", "9911000019264204", "18111590295")
//queryMemberVoiceWhitelist("898608021221C0008053")
//queryOrderInfo("990100002259001411")
//reMoveMemberVoiceWhiteList("898608021221C0008053", "9911000019264204", "15881097999")
//addMemberVoiceWhiteList("898608021221C0008053", "9911000019264204", "18140099115")
//addMemberVoiceWhiteList("898608021221C0008053", "9911000019264204", "15775320296")
ws, _ := queryMemberVoiceWhitelist("898608021221C0008053")
for _, s := range *ws {
fmt.Println(s)
}
}
// getToken 获取token
func getToken() string {
nowTime := time.Now().Unix()
if token == nil || (token.ExpireTime <= nowTime) {
lock.Lock()
if token == nil || (token.ExpireTime <= nowTime) {
if ok, t, l := requestToken(); ok {
tt := Token{}
tt.Token = t
tt.ExpireTime = nowTime + l - 60
token = &tt
}
}
lock.Unlock()
}
if token != nil {
return token.Token
}
return ""
}
func requestToken() (bool, string, int64) {
url := "https://api.iot.10086.cn/v5/ec/get/token?refresh=1&appid=" + appId + "&password=" + password + "&transid=" + greTransId()
log.Println("获取token接口:", url)
var j TokenResp
ret, err := httpGet(url)
if err != nil {
log.Println("请求中移token失败:" + err.Error())
return false, "", 0
}
err1 := json.Unmarshal(ret, &j)
if err1 != nil {
log.Println("请求中移token失败:" + err.Error())
return false, "", 0
}
if j.Status == "0" {
for _, v := range j.Result {
return true, v.Token, int64(v.TTL)
}
}
return false, "", 0
}
// findPersonVoiceWhiteNumber 个人智能网语音白名单查询
func findPersonVoiceWhiteNumber(iccId string) (*[]string, error) {
url := "https://api.iot.10086.cn/v5/ec/query/person-voice-white-number?transid=" + greTransId() + "&token=" + getToken() + "&iccid=" + iccId
log.Println(url)
ret, err := httpGet(url)
if err != nil {
log.Println("个人智能网语音白名单查询失败:" + err.Error())
return nil, err
}
var PersonVoiceWhiteNumbers struct {
Resp
Result []struct {
TotalCount string `json:"totalCount"`
WhiteNumberList []struct {
Msisdn string `json:"msisdn"`
} `json:"whiteNumberList"`
} `json:"result"`
}
err1 := json.Unmarshal(ret, &PersonVoiceWhiteNumbers)
if err1 != nil {
log.Println("个人智能网语音白名单查询失败:" + err.Error())
return nil, err
}
if PersonVoiceWhiteNumbers.Result != nil && len(PersonVoiceWhiteNumbers.Result) > 0 {
totalCount, _ := strconv.Atoi(PersonVoiceWhiteNumbers.Result[0].TotalCount)
ws := make([]string, totalCount)
for i, w := range PersonVoiceWhiteNumbers.Result[0].WhiteNumberList {
ws[i] = w.Msisdn
}
return &ws, nil
}
return nil, nil
}
// queryMemberVoiceWhitelist 成员语音白名单查询
func queryMemberVoiceWhitelist(iccId string) (*[]string, error) {
url := "https://api.iot.10086.cn/v5/ec/query/member-voice-whitelist?transid=" + greTransId() + "&token=" + getToken() + "&iccid=" + iccId + "&groupId=9911000019264204"
log.Println(url)
ret, err := httpGet(url)
if err != nil {
log.Println("成员语音白名单查询失败:" + err.Error())
return nil, err
}
var MemberVoiceWhitelist struct {
Resp
Result []struct {
TotalCount string `json:"totalCount"`
MemVoiceWhiteList []struct {
WhiteNumber string `json:"whiteNumber"`
Status string `json:"status"`
} `json:"memVoiceWhiteList"`
} `json:"result"`
}
err1 := json.Unmarshal(ret, &MemberVoiceWhitelist)
if err1 != nil {
log.Println("成员语音白名单查询失败:" + err.Error())
return nil, err
}
if MemberVoiceWhitelist.Result != nil || len(MemberVoiceWhitelist.Result) > 0 {
totalCount, _ := strconv.Atoi(MemberVoiceWhitelist.Result[0].TotalCount)
ws := make([]string, totalCount)
index := 0
for _, w := range MemberVoiceWhitelist.Result[0].MemVoiceWhiteList {
if w.Status == "1" {
ws[index] = w.WhiteNumber
index++
}
}
return &ws, nil
}
return nil, nil
}
// addMemberVoiceWhiteList 成员语音白名单配置--添加
func addMemberVoiceWhiteList(iccId, groupId, whiteNumber string) {
url := "https://api.iot.10086.cn/v5/ec/config/member-voice-whitelist?transid=" + greTransId() + "&token=" + getToken() + "&iccid=" + iccId + "&groupId=" + groupId + "&operType=1&whiteNumber=" + whiteNumber
log.Println(url)
ret, err := httpGet(url)
if err != nil {
return
}
var MemberVoiceWhiteList struct {
Resp
Result []struct {
OrderNum string `json:"orderNum"`
} `json:"result"`
}
err1 := json.Unmarshal(ret, &MemberVoiceWhiteList)
if err1 != nil {
log.Fatal(err1)
return
}
log.Println("%#v", MemberVoiceWhiteList)
}
// reMoveMemberVoiceWhiteList 成员语音白名单配置--移除
func reMoveMemberVoiceWhiteList(iccid, groupId, whiteNumber string) {
url := "https://api.iot.10086.cn/v5/ec/config/member-voice-whitelist?transid=" + greTransId() + "&token=" + getToken() + "&iccid=" + iccid + "&groupId=" + groupId + "&operType=4&whiteNumber=" + whiteNumber
log.Println(url)
ret, err := httpGet(url)
if err != nil {
return
}
var MemberVoiceWhiteList struct {
Resp
Result []struct {
OrderNum string `json:"orderNum"`
} `json:"result"`
}
err1 := json.Unmarshal(ret, &MemberVoiceWhiteList)
if err1 != nil {
log.Fatal(err1)
return
}
log.Println("%#v", MemberVoiceWhiteList)
}
// queryOrderInfo 单卡操作订单处理情况查询--查询添加或者移除白名单是否成功
func queryOrderInfo(orderNum string) {
url := "https://api.iot.10086.cn/v5/ec/query/order-info?transid=" + greTransId() + "&token=" + getToken() + "&orderNum=" + orderNum
log.Println(url)
ret, err := httpGet(url)
if err != nil {
return
}
var OrderInfo struct {
Resp
Result []struct {
OrderInfo struct {
OrderNum string `json:"orderNum"`
Status string `json:"status"`
StatusDate string `json:"statusDate"`
CreateDate string `json:"createDate"`
} `json:"orderInfo"`
} `json:"result"`
}
err1 := json.Unmarshal(ret, &OrderInfo)
if err1 != nil {
log.Fatal(err1)
return
}
log.Println("%#v", OrderInfo)
}
// queryGroupInfo 查询组群信息
func queryGroupInfo() {
url := "https://api.iot.10086.cn/v5/ec/query/group-info?transid=" + greTransId() + "&token=" + getToken() + "&pageSize=50&startNum=1"
log.Println(url)
httpGet(url)
}
// queryGroupByMember 成员归属群组查询
func queryGroupByMember(iccid string) { //9911000019264204
url := "https://api.iot.10086.cn/v5/ec/query/group-by-member?transid=" + greTransId() + "&token=" + getToken() + "&iccid=" + iccid
log.Println(url)
httpGet(url)
}
// greTransId 生成transid
func greTransId() string {
now := time.Now()
return appId + now.Format("20060102150405") + "00000001"
}
// get方法的http请求,返回原始字符串
func httpGet(url string) ([]byte, error) {
/*client := &http.Client{}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Add("content-type", "application/json")
rep, err := client.Do(req)
if err != nil {
log.Fatal(err)
return nil, err
}*/
rep, err := http.Get(url)
if err != nil {
log.Fatal(err)
return nil, err
}
defer rep.Body.Close()
data, err := ioutil.ReadAll(rep.Body)
if err != nil {
log.Fatal(err)
return nil, err
}
//log.Println(data)
log.Printf("%s", data)
//return string(data) //[]byte转string
return data, nil
}
package chinamobile
import (
"dc_golang_server_1/logger"
"dc_golang_server_1/thirdapi"
"encoding/json"
"errors"
"fmt"
"go.uber.org/zap"
"sync"
"time"
)
const appId = "551AIOT2021090208593466876"
const password = "RMm9rMVXUT,S"
const groupId = "9911000019264204"
var oneLinkToken tokenStruct
type tokenStruct struct {
rwLock sync.RWMutex
token string
expireTime int64 //到期时间戳。秒
}
type resp struct {
Status string `json:"status"`
Message string `json:"message"`
}
// greTransId 生成transid
func greTransId() string {
now := time.Now()
return appId + now.Format("20060102150405") + "00000001"
}
func requestToken() string {
url := "https://api.iot.10086.cn/v5/ec/get/token?refresh=1&appid=" + appId + "&password=" + password + "&transid=" + greTransId()
ret := thirdapi.HttpGet(url)
if ret == nil {
return ""
}
var tokenResp struct {
resp
Result []struct {
Token string `json:"token"`
TTL int64 `json:"ttl"`
} `json:"result"`
}
err1 := json.Unmarshal(ret, &tokenResp)
if err1 != nil {
logger.LogHttpClient.Error("oneLink requestToken 1",
zap.String("Url", url),
zap.Error(err1))
return ""
}
if tokenResp.Status == "0" {
if len(tokenResp.Result) > 0 {
if len(tokenResp.Result[0].Token) > 0 {
if tokenResp.Result[0].TTL > 60 { // 至少 S,TTL太短的话没意义
expire := time.Now().Unix() + tokenResp.Result[0].TTL - 60 // 到期时间-60秒,稳当些
oneLinkToken.rwLock.Lock() // 先拿写锁
//if token.expireTime > expire { // 原来的token有效时间居然更长
// token.rwLock.Unlock()
// return true
//}
oneLinkToken.token = tokenResp.Result[0].Token
oneLinkToken.expireTime = expire
oneLinkToken.rwLock.Unlock()
return tokenResp.Result[0].Token
} // if j.Result[0].TTL > 1 {
} // if len(j.Result[0].Token)>0 {
} // if len(j.Result)>0 {
} else { // if j.Status == "0" {
logger.LogHttpClient.Error("oneLink requestToken 2",
zap.String("Url", url),
zap.String("Status", tokenResp.Status),
zap.String("Massage", tokenResp.Message))
}
return ""
}
// getToken 获取token
func getToken() (t string) {
// 先取内存头的
oneLinkToken.rwLock.RLock()
if len(oneLinkToken.token) > 0 && oneLinkToken.expireTime > time.Now().Unix() {
t = oneLinkToken.token
oneLinkToken.rwLock.RUnlock()
return
}
oneLinkToken.rwLock.RUnlock()
// 内存头的不对
return requestToken()
}
// QueryMemberVoiceWhitelist 成员语音白名单查询
func QueryMemberVoiceWhitelist(iccId string) ([]string, bool) {
t := getToken()
if len(t) == 0 {
return nil, false
}
url := "https://api.iot.10086.cn/v5/ec/query/member-voice-whitelist?transid=" + greTransId() + "&token=" + getToken() + "&iccid=" + iccId + "&groupId=" + groupId
ret := thirdapi.HttpGet(url)
if ret == nil {
return nil, false
}
//fmt.Println(string(ret))
var memberVoiceWhitelist struct {
resp
Result []struct {
TotalCount string `json:"totalCount"`
MemVoiceWhiteList []struct {
WhiteNumber string `json:"whiteNumber"`
Status string `json:"status"`
} `json:"memVoiceWhiteList"`
} `json:"result"`
}
err := json.Unmarshal(ret, &memberVoiceWhitelist)
if err != nil {
logger.LogHttpClient.Error("oneLink QueryMemberVoiceWhitelist 1",
zap.String("Url", url),
zap.Error(err))
return nil, false
}
fmt.Println("oneLink查询成员语音白名单:", iccId, memberVoiceWhitelist) // todo
//if memberVoiceWhitelist.Result != nil && len(memberVoiceWhitelist.Result) > 0 {
// //fmt.Println()
// //ws := make([]string, totalCount)
// //index := 0
// //for _, w := range MemberVoiceWhitelist.Result[0].MemVoiceWhiteList {
// // if w.Status == "1" {
// // ws[index] = w.WhiteNumber
// // index++
// // }
// //}
// //return &ws, nil
//}
return nil, false
}
//// findPersonVoiceWhiteNumber 个人智能网语音白名单查询
//func findPersonVoiceWhiteNumber(iccId string) (*[]string, error) {
// url := "https://api.iot.10086.cn/v5/ec/query/person-voice-white-number?transid=" + greTransId() + "&token=" + getToken() + "&iccid=" + iccId
// log.Println(url)
// ret, err := httpGet(url)
// if err != nil {
// log.Println("个人智能网语音白名单查询失败:" + err.Error())
// return nil, err
// }
//
// var PersonVoiceWhiteNumbers struct {
// Resp
// Result []struct {
// TotalCount string `json:"totalCount"`
// WhiteNumberList []struct {
// Msisdn string `json:"msisdn"`
// } `json:"whiteNumberList"`
// } `json:"result"`
// }
//
// err1 := json.Unmarshal(ret, &PersonVoiceWhiteNumbers)
// if err1 != nil {
// log.Println("个人智能网语音白名单查询失败:" + err.Error())
// return nil, err
// }
//
// if PersonVoiceWhiteNumbers.Result != nil && len(PersonVoiceWhiteNumbers.Result) > 0 {
// totalCount, _ := strconv.Atoi(PersonVoiceWhiteNumbers.Result[0].TotalCount)
// ws := make([]string, totalCount)
// for i, w := range PersonVoiceWhiteNumbers.Result[0].WhiteNumberList {
// ws[i] = w.Msisdn
// }
// return &ws, nil
// }
// return nil, nil
//}
//
// AddMemberVoiceWhiteList 成员语音白名单配置(添加)--opType="1"添加,添加时iccID只能一个
func AddMemberVoiceWhiteList(iccId, whiteNumber string) error {
url := "https://api.iot.10086.cn/v5/ec/setting/member-voice-whitelist?transid=" +
greTransId() + "&token=" + getToken() +
"&iccid=" + iccId +
"&groupId=" + groupId +
"&operType=1&whiteNumber=" + whiteNumber
ret := thirdapi.HttpGet(url)
if ret == nil {
return errors.New("移动服务器请求失败,请稍后重试")
}
var memberVoiceWhiteList struct {
resp
Result []struct {
OrderNum string `json:"orderNum"`
} `json:"result"`
}
err := json.Unmarshal(ret, &memberVoiceWhiteList)
if err != nil {
logger.LogHttpClient.Error("oneLink AddMemberVoiceWhiteList 1",
zap.String("Url", url),
zap.Error(err))
return errors.New("移动服务器响应数据异常")
}
if memberVoiceWhiteList.Status != "0" {
logger.LogHttpClient.Error("oneLink MemberVoiceWhiteList 2",
zap.String("Url", url),
zap.String("errMsg", memberVoiceWhiteList.Message))
return errors.New(memberVoiceWhiteList.Message)
}
return nil
}
// DeleteMemberVoiceWhiteList 成员语音白名单配置(删除)opType="4"删除,删除时最多两个,中间下划线分割
func DeleteMemberVoiceWhiteList(iccId, whiteNumber string) error {
url := "https://api.iot.10086.cn/v5/ec/setting/member-voice-whitelist?transid=" +
greTransId() + "&token=" + getToken() +
"&iccid=" + iccId +
"&groupId=" + groupId +
"&operType=4&whiteNumber=" + whiteNumber
ret := thirdapi.HttpGet(url)
if ret == nil {
return errors.New("移动服务器请求失败,请稍后重试")
}
var memberVoiceWhiteList struct {
resp
Result []struct {
OrderNum string `json:"orderNum"`
} `json:"result"`
}
err := json.Unmarshal(ret, &memberVoiceWhiteList)
if err != nil {
logger.LogHttpClient.Error("oneLink AddMemberVoiceWhiteList 1",
zap.String("Url", url),
zap.Error(err))
return errors.New("移动服务器响应数据异常")
}
if memberVoiceWhiteList.Status != "0" {
logger.LogHttpClient.Error("oneLink MemberVoiceWhiteList 2",
zap.String("Url", url),
zap.String("errMsg", memberVoiceWhiteList.Message))
return errors.New(memberVoiceWhiteList.Message)
}
return nil
}
//
//// queryOrderInfo 单卡操作订单处理情况查询--查询添加或者移除白名单是否成功
//func queryOrderInfo(orderNum string) {
// url := "https://api.iot.10086.cn/v5/ec/query/order-info?transid=" + greTransId() + "&token=" + getToken() + "&orderNum=" + orderNum
// log.Println(url)
// ret, err := httpGet(url)
// if err != nil {
// return
// }
//
// var OrderInfo struct {
// Resp
// Result []struct {
// OrderInfo struct {
// OrderNum string `json:"orderNum"`
// Status string `json:"status"`
// StatusDate string `json:"statusDate"`
// CreateDate string `json:"createDate"`
// } `json:"orderInfo"`
// } `json:"result"`
// }
//
// err1 := json.Unmarshal(ret, &OrderInfo)
// if err1 != nil {
// log.Fatal(err1)
// return
// }
// log.Println("%#v", OrderInfo)
//}
//
//// queryGroupInfo 查询组群信息
//func queryGroupInfo() {
// url := "https://api.iot.10086.cn/v5/ec/query/group-info?transid=" + greTransId() + "&token=" + getToken() + "&pageSize=50&startNum=1"
// log.Println(url)
// httpGet(url)
//}
//
//// queryGroupByMember 成员归属群组查询
//func queryGroupByMember(iccid string) { //9911000019264204
// url := "https://api.iot.10086.cn/v5/ec/query/group-by-member?transid=" + greTransId() + "&token=" + getToken() + "&iccid=" + iccid
// log.Println(url)
// httpGet(url)
//}
package thirdapi
import (
"dc_golang_server_1/logger"
"go.uber.org/zap"
"io/ioutil"
"net/http"
"time"
)
// get方法的http请求,返回原始字符串
func HttpGet(url string) ([]byte, error) {
//logger.LogHttpClient
func init() {
http.DefaultClient.Timeout = 15 * time.Second // 暂时全局配
}
// HttpGet get方法的http请求,返回原始字符串
func HttpGet(url string) []byte {
startTime := time.Now().UnixMilli()
rep, err := http.Get(url)
spendTime := time.Now().UnixMilli() - startTime
if err != nil {
return nil, err
logger.LogHttpClient.Error("HttpGet e1",
zap.Int64("SpendMS", spendTime),
zap.String("Url", url),
zap.Error(err))
return nil
}
defer rep.Body.Close()
data, err := ioutil.ReadAll(rep.Body)
if err != nil {
return nil, err
logger.LogHttpClient.Error("HttpGet e2",
zap.Int64("SpendMS", spendTime),
zap.String("Url", url),
zap.Error(err))
return nil
}
return data, nil
logger.LogHttpClient.Info("HttpGet",
zap.Int64("SpendMS", spendTime),
zap.String("Url", url),
zap.String("Res", string(data)))
return data
}
package tencent
import (
"dc_golang_server_1/thirdapi"
"encoding/json"
"log"
"time"
)
const appId = "551AIOT2021090208593466876"
const password = "RMm9rMVXUT,S"
var token *tokenStruct
type tokenStruct struct {
Token string
ExpireTime int64 //到期时间戳。秒
}
type resp struct {
Status string `json:"status"`
Message string `json:"message"`
}
// greTransId 生成transid
func greTransId() string {
now := time.Now()
return appId + now.Format("20060102150405") + "00000001"
}
func requestToken() (bool, string, int64) {
type tokenResp struct {
resp
Result []struct {
Token string `json:"token"`
TTL int `json:"ttl"`
} `json:"result"`
}
url := "https://api.iot.10086.cn/v5/ec/get/token?refresh=1&appid=" + appId + "&password=" + password + "&transid=" + greTransId()
ret, err := thirdapi.HttpGet(url)
if err != nil {
log.Println("请求中移token失败:" + err.Error())
return false, "", 0
}
var j tokenResp
err1 := json.Unmarshal(ret, &j)
if err1 != nil {
log.Println("请求中移token失败:" + err.Error())
return false, "", 0
}
if j.Status == "0" {
for _, v := range j.Result {
return true, v.Token, int64(v.TTL)
}
}
return false, "", 0
}
package tencent
import "errors"
func WechatCode2Session(code string) (string, error) {
var testTemp = map[string]string{
"codeTest1": "unionIDTest1",
"codeTest2": "unionIDTest2",
"codeTest3": "unionIDTest3",
"codeTest4": "unionIDTest4",
"codeTest5": "unionIDTest5",
"codeTest6": "unionIDTest6",
"codeTest7": "unionIDTest7",
"codeTest8": "unionIDTest8",
"codeTest9": "unionIDTest8",
}
import (
"dc_golang_server_1/logger"
"dc_golang_server_1/thirdapi"
"encoding/json"
"go.uber.org/zap"
)
var testTemp = map[string]string{
"codeTest1": "unionIDTest1",
"codeTest2": "unionIDTest2",
"codeTest3": "unionIDTest3",
"codeTest4": "unionIDTest4",
"codeTest5": "unionIDTest5",
"codeTest6": "unionIDTest6",
"codeTest7": "unionIDTest7",
"codeTest8": "unionIDTest8",
"codeTest9": "unionIDTest8",
}
func WechatCode2SessionTest(code string) string {
if len(testTemp[code]) > 0 {
return testTemp[code], nil
return testTemp[code]
} else {
return "", errors.New("code无效")
return ""
}
}
//func JsCode2session(code string) (responseData WxOAuth2ResponseData, err error) {
// var NAME = "微信授权"
// var name = NAME+"-code2Session"
// var url = "https://web.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${secret}&js_code=${code}&grant_type=authorization_code"
// baseWechatPayConfig := getBaseWechatPayConfig(appId)
// url = strings.ReplaceAll(url,"${appId}",baseWechatPayConfig.appId)
// url = strings.ReplaceAll(url,"${secret}",baseWechatPayConfig.secret)
// url = strings.ReplaceAll(url,"${code}",code)
// logger.Log.Debug(name,
// zap.String("url", url))
// request, err := http.NewRequest(http.MethodGet, url,nil)
// client := http.DefaultClient
// response, err := client.Do(request)
// if err != nil {
// return responseData, err
// }
// defer func() {
// response.Body.Close()
// }()
// bodyBytes, err := ioutil.ReadAll(response.Body)
// logger.Log.Debug(name,
// zap.String("url", url),
// zap.String("response", string(bodyBytes)))
// if err != nil {
// return responseData, err
// }
// if err = json.Unmarshal(bodyBytes, &responseData); err != nil {
// return responseData, err
// }
// if responseData.Errmsg != "" {
// return responseData, errors.New(responseData.Errmsg)
// }
// return responseData, nil
//}
const weAppId = "wx99b75b4bdb31b3c3"
const weAppSecret = "e8968ce035e2ca2599c84ea36bad77cc"
type wxOAuth2ResponseDataStruct struct {
Openid string `json:"openid"`
SessionKey string `json:"session_key"`
UnionID string `json:"unionid"`
ErrCode int32 `json:"errcode"`
ErrMsg string `json:"errmsg"`
}
// WechatCode2Session 微信授权-code2Session
func WechatCode2Session(code string) (unionID, openID, sessionKey string) {
var url = "https://api.weixin.qq.com/sns/jscode2session?appid=" +
weAppId + "&secret=" + weAppSecret + "&js_code=" + code + "&grant_type=authorization_code"
ret := thirdapi.HttpGet(url)
if ret == nil {
return "", "", ""
}
var res wxOAuth2ResponseDataStruct
if err := json.Unmarshal(ret, &res); err != nil {
logger.LogHttpClient.Error("WechatCode2Session",
zap.String("code", code),
zap.String("ret", string(ret)),
zap.Error(err))
return "", "", ""
}
if res.ErrCode == 0 {
return res.UnionID, res.Openid, res.SessionKey
} else {
logger.LogHttpClient.Error("WechatCode2Session",
zap.String("code", code),
zap.Int32("ErrCode", res.ErrCode),
zap.String("ErrMsg", res.ErrMsg))
return "", "", ""
}
}
package config
package setting
import (
"go.uber.org/zap/zapcore"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment