Commit 79bfae0c by zhangjiec

调整目录结构

parent 4bf1f194
package api_public package api_public
import ( import (
"dc_golang_server_1/cache" "dc_golang_server_1/api"
"dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
"dc_golang_server_1/web"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"go.uber.org/zap" "go.uber.org/zap"
"net/http" "net/http"
...@@ -15,12 +16,12 @@ import ( ...@@ -15,12 +16,12 @@ import (
// @Summary 获取全国省份列表 [complete] // @Summary 获取全国省份列表 [complete]
// @Description 获取带首字母的省份列表 // @Description 获取带首字母的省份列表
// @Product json // @Product json
// @Success 0 {object} []cache.DistrictStruct "按首字母排序好的列表,可直接用作展示" // @Success 0 {object} []model.CacheBDistrictStruct "按首字母排序好的列表,可直接用作展示"
// @Router /base/province [GET] // @Router /base/province [GET]
// @Security ApiKeyAuth // @Security ApiKeyAuth
func GetProvinceList(c *gin.Context) { func GetProvinceList(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
"data": cache.ProvinceMap, "data": cache.ProvinceMap,
}) })
} }
...@@ -31,15 +32,15 @@ func GetProvinceList(c *gin.Context) { ...@@ -31,15 +32,15 @@ func GetProvinceList(c *gin.Context) {
// @Description 获取带首字母的城市列表 // @Description 获取带首字母的城市列表
// @Param provinceID path integer true "省份id" // @Param provinceID path integer true "省份id"
// @Product json // @Product json
// @Success 0 {object} []cache.DistrictStruct "按首字母排序好的列表,可直接用作展示" // @Success 0 {object} []model.CacheBDistrictStruct "按首字母排序好的列表,可直接用作展示"
// @Router /base/city/{provinceID} [GET] // @Router /base/city/{provinceID} [GET]
// @Security ApiKeyAuth // @Security ApiKeyAuth
func GetCityList(c *gin.Context) { func GetCityList(c *gin.Context) {
para, _ := strconv.Atoi(c.Param("id")) para, _ := strconv.Atoi(c.Param("id"))
v, _ := cache.CityMap.Load(uint32(para)) // 如果查不到就直接返回空data v, _ := cache.CityMap.Load(uint32(para)) // 如果查不到就直接返回空data
// data, _ := v.([]cache.DistrictStruct) // data, _ := v.([]model.CacheBDistrictStruct)
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
"data": v, "data": v,
}) })
} }
...@@ -50,13 +51,13 @@ func GetCityList(c *gin.Context) { ...@@ -50,13 +51,13 @@ func GetCityList(c *gin.Context) {
// @Description 获取带首字母的城市列表 // @Description 获取带首字母的城市列表
// @Param cityID path integer true "城市ID" // @Param cityID path integer true "城市ID"
// @Product json // @Product json
// @Success 0 {object} []cache.DistrictStruct "按首字母排序好的列表,可直接用作展示" // @Success 0 {object} []model.CacheBDistrictStruct "按首字母排序好的列表,可直接用作展示"
// @Router /base/county/{cityID} [GET] // @Router /base/county/{cityID} [GET]
// @Security ApiKeyAuth // @Security ApiKeyAuth
func GetCountyList(c *gin.Context) { func GetCountyList(c *gin.Context) {
para, _ := strconv.Atoi(c.Param("id")) para, _ := strconv.Atoi(c.Param("id"))
v, _ := cache.CountyMap.Load(uint32(para)) // 如果查不到就直接返回空data v, _ := cache.CountyMap.Load(uint32(para)) // 如果查不到就直接返回空data
// data, _ := v.([]cache.DistrictStruct) // data, _ := v.([]model.CacheBDistrictStruct)
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": 0, "code": 0,
"data": v, "data": v,
...@@ -81,8 +82,8 @@ func GetAreaByCounty(c *gin.Context) { ...@@ -81,8 +82,8 @@ func GetAreaByCounty(c *gin.Context) {
countyID, err := strconv.Atoi(c.Param("id")) countyID, err := strconv.Atoi(c.Param("id"))
if err != nil { if err != nil {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.ErrorReqParaFormat, "code": api.ErrorReqParaFormat,
"message": web.CodeMsg[web.ErrorReqParaFormat], "message": api.CodeMsg[api.ErrorReqParaFormat],
}) })
return return
} }
...@@ -92,8 +93,8 @@ func GetAreaByCounty(c *gin.Context) { ...@@ -92,8 +93,8 @@ func GetAreaByCounty(c *gin.Context) {
zap.String("Src", "GetAreaByCounty"), zap.String("Src", "GetAreaByCounty"),
zap.Int("countyID", countyID)) zap.Int("countyID", countyID))
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.ErrorSystemErr, "code": api.ErrorSystemErr,
"message": web.CodeMsg[web.ErrorSystemErr], "message": api.CodeMsg[api.ErrorSystemErr],
}) })
return return
} }
...@@ -101,20 +102,13 @@ func GetAreaByCounty(c *gin.Context) { ...@@ -101,20 +102,13 @@ func GetAreaByCounty(c *gin.Context) {
testRole, ok := cache.GetWechatCustomerTestRole(userID.(uint32)) testRole, ok := cache.GetWechatCustomerTestRole(userID.(uint32))
if ok == false { if ok == false {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.ErrorUserTokenWrong, "code": api.ErrorUserTokenWrong,
"message": web.CodeMsg[web.ErrorUserTokenWrong], "message": api.CodeMsg[api.ErrorUserTokenWrong],
}) })
return return
} }
areaList, ok := cache.GetCountyAreaMap(uint32(countyID)) areaList := cache.GetCountyAreaMap(uint32(countyID))
if ok == false {
c.JSON(http.StatusOK, gin.H{
"code": web.ErrorReqPara,
"message": web.CodeMsg[web.ErrorReqPara] + ",区县id=" + strconv.Itoa(countyID),
})
return
}
var data []countyAreaRes var data []countyAreaRes
...@@ -126,7 +120,7 @@ func GetAreaByCounty(c *gin.Context) { ...@@ -126,7 +120,7 @@ func GetAreaByCounty(c *gin.Context) {
} }
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
"data": data, "data": data,
}) })
} }
...@@ -181,7 +175,7 @@ func GetAreaByLocation(c *gin.Context) { ...@@ -181,7 +175,7 @@ func GetAreaByLocation(c *gin.Context) {
var data []locationAreaRes var data []locationAreaRes
v, _ := cache.AreaMap.Load(uint32(14)) // todo 根据经纬度计算距离 还要看status 和 用户的权限 v, _ := cache.AreaMap.Load(uint32(14)) // todo 根据经纬度计算距离 还要看status 和 用户的权限
if a, ok := v.(cache.AreaStruct); ok { //类型断言正确 if a, ok := v.(model.CacheBAreaStruct); ok { //类型断言正确
data = append(data, locationAreaRes{ data = append(data, locationAreaRes{
a.Name, a.Name,
"温江区", "温江区",
...@@ -190,7 +184,7 @@ func GetAreaByLocation(c *gin.Context) { ...@@ -190,7 +184,7 @@ func GetAreaByLocation(c *gin.Context) {
} }
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
"data": data, "data": data,
}) })
} }
package api_we package api_we
import ( import (
"dc_golang_server_1/web" "dc_golang_server_1/api"
//"dc_golang_server_1/web"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"net/http" "net/http"
"time" "time"
) )
// DeleteCardUser 主家长删除一个学生
// @Tags 家长微信
// @Summary 主家长删除一个学生
// @Description 传学生ID至后台,后台返回成功失败
// @Produce json
// @Param id path integer true "学生ID"
// @Success 0
// @Router /we/carduser/{id} [DELETE]
// @Security ApiKeyAuth
func DeleteCardUser(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"code": web.Success,
})
}
type bindCardUserRes struct { type bindCardUserRes struct {
Master bool `json:"master" example:"false"` //true:本来就是主家长,false:已成功绑定成副家长 Master bool `json:"master" example:"false"` //true:本来就是主家长,false:已成功绑定成副家长
ID uint32 `json:"id"` // 学生ID ID uint32 `json:"id"` // 学生ID
...@@ -49,7 +33,7 @@ type bindCardUserRes struct { ...@@ -49,7 +33,7 @@ type bindCardUserRes struct {
func BindCardUser(c *gin.Context) { func BindCardUser(c *gin.Context) {
res := bindCardUserRes{} res := bindCardUserRes{}
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
"data": res, "data": res,
}) })
} }
...@@ -65,7 +49,7 @@ func BindCardUser(c *gin.Context) { ...@@ -65,7 +49,7 @@ func BindCardUser(c *gin.Context) {
// @Security ApiKeyAuth // @Security ApiKeyAuth
func DeleteBindCardUser(c *gin.Context) { func DeleteBindCardUser(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
}) })
} }
...@@ -88,7 +72,7 @@ type wechatCardUsersTrendType struct { ...@@ -88,7 +72,7 @@ type wechatCardUsersTrendType struct {
func GetCardUsersTrend(c *gin.Context) { func GetCardUsersTrend(c *gin.Context) {
//id, _ := strconv.Atoi(c.Param("id")) //id, _ := strconv.Atoi(c.Param("id"))
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
"data": [20]wechatCardUsersTrendType{}, "data": [20]wechatCardUsersTrendType{},
}) })
} }
...@@ -124,7 +108,7 @@ type slaveWeUserRes struct { ...@@ -124,7 +108,7 @@ type slaveWeUserRes struct {
// @Security ApiKeyAuth // @Security ApiKeyAuth
func GetBindCardUser(c *gin.Context) { func GetBindCardUser(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
"data": []slaveWeUserRes{}, "data": []slaveWeUserRes{},
}) })
} }
...@@ -141,7 +125,7 @@ func GetBindCardUser(c *gin.Context) { ...@@ -141,7 +125,7 @@ func GetBindCardUser(c *gin.Context) {
// @Security ApiKeyAuth // @Security ApiKeyAuth
func CardUserShareCode(c *gin.Context) { func CardUserShareCode(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
"data": "todo", "data": "todo",
}) })
} }
...@@ -157,7 +141,7 @@ func CardUserShareCode(c *gin.Context) { ...@@ -157,7 +141,7 @@ func CardUserShareCode(c *gin.Context) {
//// @Security ApiKeyAuth //// @Security ApiKeyAuth
//func PutCardUserShareOn(c *gin.Context) { //func PutCardUserShareOn(c *gin.Context) {
// c.JSON(http.StatusOK, gin.H{ // c.JSON(http.StatusOK, gin.H{
// "code": web.Success, // "code": api.Success,
// }) // })
//} //}
...@@ -172,7 +156,7 @@ func CardUserShareCode(c *gin.Context) { ...@@ -172,7 +156,7 @@ func CardUserShareCode(c *gin.Context) {
//// @Security ApiKeyAuth //// @Security ApiKeyAuth
//func PutCardUserShareOff(c *gin.Context) { //func PutCardUserShareOff(c *gin.Context) {
// c.JSON(http.StatusOK, gin.H{ // c.JSON(http.StatusOK, gin.H{
// "code": web.Success, // "code": api.Success,
// }) // })
//} //}
...@@ -188,7 +172,7 @@ func CardUserShareCode(c *gin.Context) { ...@@ -188,7 +172,7 @@ func CardUserShareCode(c *gin.Context) {
// @Security ApiKeyAuth // @Security ApiKeyAuth
func DeleteSlaveWeUser(c *gin.Context) { func DeleteSlaveWeUser(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
}) })
} }
...@@ -204,7 +188,7 @@ func DeleteSlaveWeUser(c *gin.Context) { ...@@ -204,7 +188,7 @@ func DeleteSlaveWeUser(c *gin.Context) {
//// @Security ApiKeyAuth //// @Security ApiKeyAuth
//func DeleteAllSlaveWeUser(c *gin.Context) { //func DeleteAllSlaveWeUser(c *gin.Context) {
// c.JSON(http.StatusOK, gin.H{ // c.JSON(http.StatusOK, gin.H{
// "code": web.Success, // "code": api.Success,
// }) // })
//} //}
...@@ -234,7 +218,7 @@ type PutCardUserReq struct { ...@@ -234,7 +218,7 @@ type PutCardUserReq struct {
// @Security ApiKeyAuth // @Security ApiKeyAuth
func PutCardUser(c *gin.Context) { func PutCardUser(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
}) })
} }
...@@ -251,7 +235,7 @@ func PutCardUser(c *gin.Context) { ...@@ -251,7 +235,7 @@ func PutCardUser(c *gin.Context) {
// @Security ApiKeyAuth // @Security ApiKeyAuth
func CardLoss(c *gin.Context) { func CardLoss(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
}) })
} }
...@@ -268,7 +252,7 @@ func CardLoss(c *gin.Context) { ...@@ -268,7 +252,7 @@ func CardLoss(c *gin.Context) {
// @Security ApiKeyAuth // @Security ApiKeyAuth
func CardBind(c *gin.Context) { func CardBind(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
}) })
} }
...@@ -284,7 +268,7 @@ func CardBind(c *gin.Context) { ...@@ -284,7 +268,7 @@ func CardBind(c *gin.Context) {
// @Security ApiKeyAuth // @Security ApiKeyAuth
func DeleteCardBind(c *gin.Context) { func DeleteCardBind(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
}) })
} }
...@@ -314,7 +298,7 @@ type getPhoneCardStatusRes struct { ...@@ -314,7 +298,7 @@ type getPhoneCardStatusRes struct {
// @Security ApiKeyAuth // @Security ApiKeyAuth
func GetPhoneCardStatus(c *gin.Context) { func GetPhoneCardStatus(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
"data": getPhoneCardStatusRes{}, "data": getPhoneCardStatusRes{},
}) })
} }
...@@ -346,7 +330,7 @@ type getCallRecordRes struct { ...@@ -346,7 +330,7 @@ type getCallRecordRes struct {
// @Security ApiKeyAuth // @Security ApiKeyAuth
func GetCallRecord(c *gin.Context) { func GetCallRecord(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
"data": [2]getCallRecordRes{}, "data": [2]getCallRecordRes{},
}) })
} }
...@@ -364,7 +348,7 @@ func GetCallRecord(c *gin.Context) { ...@@ -364,7 +348,7 @@ func GetCallRecord(c *gin.Context) {
// @Security ApiKeyAuth // @Security ApiKeyAuth
func AddFamilyNum(c *gin.Context) { func AddFamilyNum(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
}) })
} }
...@@ -382,7 +366,7 @@ func AddFamilyNum(c *gin.Context) { ...@@ -382,7 +366,7 @@ func AddFamilyNum(c *gin.Context) {
// @Security ApiKeyAuth // @Security ApiKeyAuth
func PutFamilyNum(c *gin.Context) { func PutFamilyNum(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
}) })
} }
...@@ -399,6 +383,6 @@ func PutFamilyNum(c *gin.Context) { ...@@ -399,6 +383,6 @@ func PutFamilyNum(c *gin.Context) {
// @Security ApiKeyAuth // @Security ApiKeyAuth
func DeleteFamilyNum(c *gin.Context) { func DeleteFamilyNum(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{ c.JSON(http.StatusOK, gin.H{
"code": web.Success, "code": api.Success,
}) })
} }
package web package api
import ( import (
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
......
package web package api
const ( const (
Success = 0 Success = 0
......
package web package api
import ( import (
"dc_golang_server_1/cache" "dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/util" "dc_golang_server_1/util"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"math/rand" "math/rand"
...@@ -247,7 +247,7 @@ func JeffWTAdmin() gin.HandlerFunc { ...@@ -247,7 +247,7 @@ func JeffWTAdmin() gin.HandlerFunc {
} }
} }
//package web //package api
// //
//import ( //import (
// "dc_golang_server_1/cache" // "dc_golang_server_1/cache"
......
package router package router
import ( import (
"dc_golang_server_1/config" "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_we"
_ "dc_golang_server_1/docs" _ "dc_golang_server_1/docs"
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
"dc_golang_server_1/web" config2 "dc_golang_server_1/util/config"
"dc_golang_server_1/web/api_admin"
"dc_golang_server_1/web/api_public"
"dc_golang_server_1/web/api_we"
"fmt" "fmt"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/swaggo/gin-swagger" "github.com/swaggo/gin-swagger"
...@@ -16,18 +16,18 @@ import ( ...@@ -16,18 +16,18 @@ import (
) )
func InitRouter() { //*gin.Engine{ func InitRouter() { //*gin.Engine{
gin.SetMode(config.HttpServerMode) gin.SetMode(config2.HttpServerMode)
r := gin.New() r := gin.New()
r.Use(logger.HttpGinLog(), gin.Recovery()) r.Use(logger.HttpGinLog(), gin.Recovery())
r.Use(web.Cors()) //全局跨域 局部跨域的话在路由组里面去添加 r.Use(api.Cors()) //全局跨域 局部跨域的话在路由组里面去添加
//r.Use(CheckToken()) //jwt 还是在对应需要token的路由组添加 //r.Use(CheckToken()) //jwt 还是在对应需要token的路由组添加
if config.HttpServerSwagger { if config2.HttpServerSwagger {
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler)) r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
} }
base := r.Group("base/") base := r.Group("base/")
base.Use(web.JeffWTPublic()) base.Use(api.JeffWTPublic())
{ {
base.GET("province", api_public.GetProvinceList) base.GET("province", api_public.GetProvinceList)
base.GET("city/:id", api_public.GetCityList) base.GET("city/:id", api_public.GetCityList)
...@@ -38,7 +38,7 @@ func InitRouter() { //*gin.Engine{ ...@@ -38,7 +38,7 @@ func InitRouter() { //*gin.Engine{
r.POST("we/login/:code", api_we.WeLogin) r.POST("we/login/:code", api_we.WeLogin)
wechat := r.Group("we/") wechat := r.Group("we/")
wechat.Use(web.JeffWTWechat()) wechat.Use(api.JeffWTWechat())
{ // 需要token的 { // 需要token的
wechat.POST("carduser", api_we.CreateCardUser) //创建学生 wechat.POST("carduser", api_we.CreateCardUser) //创建学生
wechat.DELETE("carduser/:id", api_we.DeleteCardUser) //删除学生 wechat.DELETE("carduser/:id", api_we.DeleteCardUser) //删除学生
...@@ -71,15 +71,15 @@ func InitRouter() { //*gin.Engine{ ...@@ -71,15 +71,15 @@ func InitRouter() { //*gin.Engine{
// r.POST("ad/login", api_we.AdminLogin) // r.POST("ad/login", api_we.AdminLogin)
admin := r.Group("ad/") admin := r.Group("ad/")
// admin.Use(web.JeffWTAdmin()) // admin.Use(api.JeffWTAdmin())
{ {
admin.POST("area", api_admin.CreateArea) // 新建一个学校 admin.POST("area", api_admin.CreateArea) // 新建一个学校
// admin.GET("cache", api_cache.GetCacheMap) // 获取缓存内容 // admin.GET("cache", api_cache.GetCacheMap) // 获取缓存内容
} }
fmt.Println(time.Now(), "server is running:swagger", config.HttpServerSwagger) fmt.Println(time.Now(), "server is running:swagger", config2.HttpServerSwagger)
err := r.Run(config.HttpServerPort) err := r.Run(config2.HttpServerPort)
if err != nil { if err != nil {
panic(err) panic(err)
} }
......
package cache package cache
import ( import (
"dc_golang_server_1/data_db_cache/model"
"sync" "sync"
"time" "time"
) )
// ProvinceMap /*********************************************************全国行政区域**/------------------------OK // ProvinceMap /*********************************************************全国行政区域**/------------------------OK
var ProvinceMap []DistrictStruct // 省份列表[]District var ProvinceMap []model.CacheBDistrictStruct // 省份列表[]model.CacheBDistrictStruct
var CityMap sync.Map // 城市列表map[uint32][]District //省份ID作为KEY var CityMap sync.Map // 城市列表map[uint32][]model.CacheBDistrictStruct //省份ID作为KEY
var CountyMap sync.Map // 区县列表map[uint32][]District //城市ID作为KEY var CountyMap sync.Map // 区县列表map[uint32][]model.CacheBDistrictStruct //城市ID作为KEY
type DistrictStruct struct { //type CacheBDistrictStruct struct {
Id uint32 `json:"id" example:"1"` // Id uint32 `json:"id" example:"1"`
Name string `json:"name" example:"四川省"` // Name string `json:"name" example:"四川省"`
Initial string `json:"initial" example:"S"` // Initial string `json:"initial" example:"S"`
} //}
// CountyAreaMap /******************************************************************区县学校列表**/ // CountyAreaMap /******************************************************************区县学校列表**/
var CountyAreaMap sync.Map //map[uint32][[]uint32] 区县ID作为KEY,[]area_id 作为Value var CountyAreaMap sync.Map //map[uint32][[]uint32] 区县ID作为KEY,[]area_id 作为Value
// var LockCountyAreaMap bool // todo 正规的做法是用 map[区县ID]bool
// TestAreaMap /******************************************************************测试校区列表**/ // TestAreaMap /******************************************************************测试校区列表**/
// AreaMap /******************************************************区域(校区)**/ // AreaMap /******************************************************区域(校区)**/
var AreaMap sync.Map //area_id 作为KEY AreaStruct 作为VALUE var AreaMap sync.Map //area_id 作为KEY CacheBAreaStruct 作为VALUE
type AreaStruct struct { // AreaStruct 区域信息缓存,通过区域ID查出,后续再加支付信息 //type CacheBAreaStruct struct { // CacheBAreaStruct 区域信息缓存,通过区域ID查出,后续再加支付信息
Name string // Name string
Longitude uint32 // Longitude uint32
Latitude uint32 // Latitude uint32
CountyID uint32 // CountyID uint32
AreaService []uint32 // AreaService []uint32
Status uint8 //校区状态 0 不展示 1展示 2测试校区 // Status uint8 //校区状态 0 不展示 1展示 2测试校区
// CreatAt time.Time //}
}
// var LockAreaMapAreaService bool todo
/*********************************************************代理商**/ /*********************************************************代理商**/
//// AgentMap 代理商 //// AgentMap 代理商
...@@ -47,7 +50,7 @@ type OperatorStruct struct { ...@@ -47,7 +50,7 @@ type OperatorStruct struct {
/*---------------------------------------------------------------*/ /*---------------------------------------------------------------*/
/******************************************************区域(校区)服务信息**/ /******************************************************区域(校区)服务信息**/
var areaServiceMap sync.Map //area_service_id 作为KEY AreaStruct 作为VALUE var areaServiceMap sync.Map //area_service_id 作为KEY CacheBAreaStruct 作为VALUE
type AreaServiceStruct struct { // type AreaServiceStruct struct { //
AreaID uint32 AreaID uint32
ServiceID uint8 //服务项目 1公话 2定位 3饮水 4POS ......... ServiceID uint8 //服务项目 1公话 2定位 3饮水 4POS .........
...@@ -71,6 +74,7 @@ type AdminStruct struct { ...@@ -71,6 +74,7 @@ type AdminStruct struct {
AreaServiceAuth [][]uint32 //area_service_id,admin_role_id AreaServiceAuth [][]uint32 //area_service_id,admin_role_id
} }
// todo 加锁var LockAreaMapAreaService bool
/*---------------------------------------------------------------*/ /*---------------------------------------------------------------*/
// roleAuthMap /****************************角色权限(包含区域和系统角色)*/ // roleAuthMap /****************************角色权限(包含区域和系统角色)*/
...@@ -80,22 +84,24 @@ type RoleAuthStruct struct { ...@@ -80,22 +84,24 @@ type RoleAuthStruct struct {
MenuRole map[uint32][]uint32 // 菜单、按钮权限 MenuRole map[uint32][]uint32 // 菜单、按钮权限
} }
// todo 加锁
/***************************************************微信用户(家长)**/ //------------------------OK /***************************************************微信用户(家长)**/ //------------------------OK
var WechatCustomerUnionIDToIDMAP sync.Map // UnionID作为KEY(string),微信用户ID作为VALUE(uint32) var WechatCustomerUnionIDToIDMAP sync.Map // UnionID作为KEY(string),微信用户ID作为VALUE(uint32)
var WechatCustomerMap sync.Map // 微信的WechatUserID(uint32)作为KEY var WechatCustomerMap sync.Map // 微信的WechatUserID(uint32)作为KEY
type WechatCustomerStruct struct { //type CacheUWeCustomerStruct struct {
TokenCreatTime int64 // TokenCreatTime int64
TestRole bool // 测试用户(可看到测试校区) // TestRole bool // 测试用户(可看到测试校区)
WePhone string // 手机号 // WePhone string // 手机号
Nickname string // 微信昵称 // Nickname string // 微信昵称
AvatarURL string // 头像链接 // AvatarURL string // 头像链接
MasterCardUserID []uint32 // 自己创建的学生用户 // MasterCardUserID []uint32 // 自己创建的学生用户
SlaveCardUserID []uint32 // 被邀请查看的学生用户 // SlaveCardUserID []uint32 // 被邀请查看的学生用户
} //}
// todo 加锁
/****************************************************************/ /****************************************************************/
/***************************************************卡用户(学生、教师、职工)**/ //CardUserMap /***************************************************卡用户(学生、教师、职工)**/
var CardUserMap sync.Map //卡用户 CardUserID卡用户ID(uint32) 作为KEY 纯卡用户可以不绑定微信 var CardUserMap sync.Map //卡用户 CardUserID卡用户ID(uint32) 作为KEY 纯卡用户可以不绑定微信
type CardUserType struct { type CardUserType struct {
MasterWechatUserID uint32 MasterWechatUserID uint32
...@@ -121,6 +127,7 @@ type CardUserType struct { ...@@ -121,6 +127,7 @@ type CardUserType struct {
IcCardID uint32 IcCardID uint32
} }
// todo 加锁SlaveWechatUserID
/*---------------------------------------------------------------*/ /*---------------------------------------------------------------*/
/*******************************************************电话设备**/ /*******************************************************电话设备**/
...@@ -148,6 +155,7 @@ type FamilyOnePerson struct { ...@@ -148,6 +155,7 @@ type FamilyOnePerson struct {
Nickname string Nickname string
} }
// todo 加锁FamilyNum
/*---------------------------------------------------------------*/ /*---------------------------------------------------------------*/
/***************************************************卡用户动态**/ /***************************************************卡用户动态**/
...@@ -162,7 +170,7 @@ type CardUserTrendType struct { ...@@ -162,7 +170,7 @@ type CardUserTrendType struct {
/*---------------------------------------------------------------*/ /*---------------------------------------------------------------*/
func Init() { func Init() {
initBCityMaps() // 初始化行政区域省市区缓存 initBDistrictMaps() // 初始化行政区域省市区缓存
initAreaMapAndCountyAreaMap() initAreaMapAndCountyAreaMap()
initWechatCustomerMap() initWechatCustomerMap()
......
package cache package cache
import ( import (
"dc_golang_server_1/dbmodel" "dc_golang_server_1/data_db_cache/dbdao"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
"fmt" "fmt"
"go.uber.org/zap" "go.uber.org/zap"
...@@ -25,8 +26,8 @@ import ( ...@@ -25,8 +26,8 @@ import (
func initAreaMapAndCountyAreaMap() { func initAreaMapAndCountyAreaMap() {
fmt.Println(time.Now(), "cache: initAreaMap begin") fmt.Println(time.Now(), "cache: initAreaMap begin")
var areaID uint32 var areaID uint32
var temp AreaStruct var temp model.CacheBAreaStruct
rows, err := dbmodel.PgDb.Query("SELECT id,county_id,name,longitude,latitude,status FROM b_area") // rows, err := dbdao.PgDb.Query("SELECT id,county_id,name,longitude,latitude,status FROM b_area") //
defer rows.Close() defer rows.Close()
if err != nil { if err != nil {
log.Panicln("SelectAreaToMap rows", err) log.Panicln("SelectAreaToMap rows", err)
...@@ -59,7 +60,7 @@ func initAreaMapAndCountyAreaMap() { ...@@ -59,7 +60,7 @@ func initAreaMapAndCountyAreaMap() {
func GetAreaMapName(areaID uint32, test bool) string { func GetAreaMapName(areaID uint32, test bool) string {
if v, ok := AreaMap.Load(areaID); ok { if v, ok := AreaMap.Load(areaID); ok {
if data, ok := v.(AreaStruct); ok { if data, ok := v.(model.CacheBAreaStruct); ok {
if data.Status == 1 || (data.Status == 2 && test) { if data.Status == 1 || (data.Status == 2 && test) {
return data.Name return data.Name
} }
...@@ -79,9 +80,9 @@ func GetAreaMapName(areaID uint32, test bool) string { ...@@ -79,9 +80,9 @@ func GetAreaMapName(areaID uint32, test bool) string {
return "" return ""
} }
func GetAreaMapInfo(areaID uint32, info *AreaStruct) bool { func GetAreaMapInfo(areaID uint32, info *model.CacheBAreaStruct) bool {
if v, ok := AreaMap.Load(areaID); ok { if v, ok := AreaMap.Load(areaID); ok {
if *info, ok = v.(AreaStruct); ok { if *info, ok = v.(model.CacheBAreaStruct); ok {
return true return true
} else { } else {
AreaMap.Delete(areaID) AreaMap.Delete(areaID)
......
package cache package cache
import ( import (
"dc_golang_server_1/dbmodel" "dc_golang_server_1/data_db_cache/dbdao"
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
"fmt" "fmt"
"go.uber.org/zap" "go.uber.org/zap"
...@@ -13,7 +13,7 @@ func initAreaServiceMap() { ...@@ -13,7 +13,7 @@ func initAreaServiceMap() {
fmt.Println(time.Now(), "cache: initDeviceMap begin") fmt.Println(time.Now(), "cache: initDeviceMap begin")
var areaID int32 var areaID int32
var temp AreaServiceStruct var temp AreaServiceStruct
rows, err := dbmodel.PgDb.Query("SELECT id,name,status FROM b_area") //todo rows, err := dbdao.PgDb.Query("SELECT id,name,status FROM b_area") //todo
defer rows.Close() defer rows.Close()
if err != nil { if err != nil {
log.Panicln("SelectAreaToMap rows", err) log.Panicln("SelectAreaToMap rows", err)
...@@ -57,7 +57,7 @@ func GetAreaServiceInfo(areaServiceID uint32) (areaServiceInfo AreaServiceStruct ...@@ -57,7 +57,7 @@ func GetAreaServiceInfo(areaServiceID uint32) (areaServiceInfo AreaServiceStruct
var err error var err error
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
err = dbmodel.PgDb.QueryRow("SELECT name,status FROM b_area WHERE id=$1", err = dbdao.PgDb.QueryRow("SELECT name,status FROM b_area WHERE id=$1",
areaServiceID).Scan(&areaServiceInfo.Name, &areaServiceInfo.Status) //todo areaServiceID).Scan(&areaServiceInfo.Name, &areaServiceInfo.Status) //todo
if err != nil { if err != nil {
fmt.Println("GetAreaInfo SELECT:", i, err) fmt.Println("GetAreaInfo SELECT:", i, err)
......
package cache package cache
import ( import (
"dc_golang_server_1/dbmodel" "dc_golang_server_1/data_db_cache/dbdao"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
"fmt" "fmt"
"go.uber.org/zap" "go.uber.org/zap"
...@@ -11,21 +12,21 @@ import ( ...@@ -11,21 +12,21 @@ import (
) )
// 初始化行政区域缓存 // 初始化行政区域缓存
func initBCityMaps() { func initBDistrictMaps() {
fmt.Println(time.Now(), "cache: initBCityMaps begin") fmt.Println(time.Now(), "cache: initBDistrictMaps begin")
go func() bool { go func() bool {
ProvinceMap = []DistrictStruct{} //先清空原来的缓存 ProvinceMap = []model.CacheBDistrictStruct{} //先清空原来的缓存
var temp DistrictStruct var temp model.CacheBDistrictStruct
rows, err := dbmodel.PgDb.Query("SELECT id,name,initial FROM b_city WHERE level=1 ORDER BY initial,sort") rows, err := dbdao.PgDb.Query("SELECT id,name,initial FROM b_district WHERE level=1 ORDER BY initial,sort")
defer rows.Close() defer rows.Close()
if err != nil { if err != nil {
log.Panicln("ProvinceMap SELECT b_city rows", err) log.Panicln("ProvinceMap SELECT b_district rows", err)
} }
for rows.Next() { for rows.Next() {
err = rows.Scan(&temp.Id, &temp.Name, &temp.Initial) err = rows.Scan(&temp.Id, &temp.Name, &temp.Initial)
if err != nil { if err != nil {
log.Panicln("ProvinceMap SELECT b_city rows.Scan", err) log.Panicln("ProvinceMap SELECT b_district rows.Scan", err)
} }
ProvinceMap = append(ProvinceMap, temp) ProvinceMap = append(ProvinceMap, temp)
} }
...@@ -38,7 +39,7 @@ func initBCityMaps() { ...@@ -38,7 +39,7 @@ func initBCityMaps() {
selectToDistrictMap(2, &CityMap) selectToDistrictMap(2, &CityMap)
selectToDistrictMap(3, &CountyMap) selectToDistrictMap(3, &CountyMap)
fmt.Println(time.Now(), "cache: initBCityMaps OK") fmt.Println(time.Now(), "cache: initBDistrictMaps OK")
} }
func selectToDistrictMap(level uint8, tempMap *sync.Map) bool { func selectToDistrictMap(level uint8, tempMap *sync.Map) bool {
...@@ -49,22 +50,22 @@ func selectToDistrictMap(level uint8, tempMap *sync.Map) bool { ...@@ -49,22 +50,22 @@ func selectToDistrictMap(level uint8, tempMap *sync.Map) bool {
}) })
var parentID uint32 var parentID uint32
var temp DistrictStruct var temp model.CacheBDistrictStruct
rows, err := dbmodel.PgDb.Query("SELECT id,name,parent_id,initial FROM b_city WHERE level=$1 ORDER BY initial,sort", level) rows, err := dbdao.PgDb.Query("SELECT id,name,parent_id,initial FROM b_district WHERE level=$1 ORDER BY initial,sort", level)
defer rows.Close() defer rows.Close()
if err != nil { if err != nil {
log.Panicln("SELECT b_city rows", err, level) log.Panicln("SELECT b_district rows", err, level)
} }
for rows.Next() { for rows.Next() {
err = rows.Scan(&temp.Id, &temp.Name, &parentID, &temp.Initial) err = rows.Scan(&temp.Id, &temp.Name, &parentID, &temp.Initial)
if err != nil { if err != nil {
log.Panicln("SELECT b_city rows.Scan", err, level) log.Panicln("SELECT b_district rows.Scan", err, level)
} }
var bufStruct []DistrictStruct var bufStruct []model.CacheBDistrictStruct
if v, ok := tempMap.Load(parentID); ok { //map已经有了 if v, ok := tempMap.Load(parentID); ok { //map已经有了
if bufStruct, ok = v.([]DistrictStruct); ok == false { //类型断言错误 if bufStruct, ok = v.([]model.CacheBDistrictStruct); ok == false { //类型断言错误
tempMap.Delete(parentID) tempMap.Delete(parentID)
logger.Log.Error("[]DistrictStruct 类型断言错误", logger.Log.Error("[]BDistrictStruct 类型断言错误",
zap.Uint8("level", level), zap.Uint8("level", level),
zap.String("src", "selectToDistrictMap")) zap.String("src", "selectToDistrictMap"))
} }
......
package cache package cache
import ( import (
"dc_golang_server_1/dbmodel" "dc_golang_server_1/data_db_cache/dbdao"
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
"fmt" "fmt"
"go.uber.org/zap" "go.uber.org/zap"
...@@ -24,7 +24,7 @@ func initCardUserMap() { ...@@ -24,7 +24,7 @@ func initCardUserMap() {
fmt.Println(time.Now(), "cache: initCardUserMap begin") fmt.Println(time.Now(), "cache: initCardUserMap begin")
var cardUserID uint32 var cardUserID uint32
var temp CardUserType var temp CardUserType
rows, err := dbmodel.PgDb.Query("SELECT id,role,name,sex,area_id,grade,class,student_num,first_topup_at is not null FROM u_card_user") // rows, err := dbdao.PgDb.Query("SELECT id,role,name,sex,area_id,grade,class,student_num,first_topup_at is not null FROM u_card_user") //
defer rows.Close() defer rows.Close()
if err != nil { if err != nil {
log.Panicln("Select u_card_user To Map rows", err) log.Panicln("Select u_card_user To Map rows", err)
......
...@@ -5,22 +5,19 @@ import ( ...@@ -5,22 +5,19 @@ import (
"go.uber.org/zap" "go.uber.org/zap"
) )
func GetCountyAreaMap(countyID uint32) ([]uint32, bool) { func GetCountyAreaMap(countyID uint32) []uint32 {
var data []uint32 var data []uint32
if v, ok := CountyAreaMap.Load(countyID); ok { if v, ok := CountyAreaMap.Load(countyID); ok {
if data, ok = v.([]uint32); ok { if data, ok = v.([]uint32); ok {
return data, true return data
} else { } else {
CountyAreaMap.Delete(countyID)
logger.Log.Error("CountyAreaMap 类型断言错误", logger.Log.Error("CountyAreaMap 类型断言错误",
zap.String("Src", "GetCountyAreaMap"), zap.String("Src", "GetCountyAreaMap"),
zap.Uint32("countyID", countyID)) zap.Uint32("countyID", countyID))
// todoN 查库
} }
} }
return data
logger.Log.Error("CountyAreaMap 没数据",
zap.String("Src", "GetCountyAreaMap"),
zap.Uint32("countyID", countyID))
return data, false
} }
package cache package cache
import ( import (
"dc_golang_server_1/dbmodel" "dc_golang_server_1/data_db_cache/dbdao"
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
"fmt" "fmt"
"go.uber.org/zap" "go.uber.org/zap"
...@@ -13,7 +13,7 @@ func initPhone20DeviceMap() { ...@@ -13,7 +13,7 @@ func initPhone20DeviceMap() {
fmt.Println(time.Now(), "cache: initDeviceMap begin") fmt.Println(time.Now(), "cache: initDeviceMap begin")
var devID uint32 var devID uint32
var temp Phone20DeviceStruct var temp Phone20DeviceStruct
rows, err := dbmodel.PgDb.Query("SELECT id,area_service_id,allow_call_time,status FROM d_device") rows, err := dbdao.PgDb.Query("SELECT id,area_service_id,allow_call_time,status FROM d_device")
defer rows.Close() defer rows.Close()
if err != nil { if err != nil {
log.Panicln("SelectDeviceToMap rows", err) log.Panicln("SelectDeviceToMap rows", err)
...@@ -50,7 +50,7 @@ func GetPhone20Info(devID uint32) Phone20DeviceStruct { ...@@ -50,7 +50,7 @@ func GetPhone20Info(devID uint32) Phone20DeviceStruct {
var temp Phone20DeviceStruct var temp Phone20DeviceStruct
var err error var err error
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
err = dbmodel.PgDb.QueryRow("SELECT area_service_id,allow_call_time,status FROM d_phone20 WHERE id=$1", err = dbdao.PgDb.QueryRow("SELECT area_service_id,allow_call_time,status FROM d_phone20 WHERE id=$1",
devID).Scan(&temp.AreaServiceID, &temp.AllowCallTime, &temp.Status) devID).Scan(&temp.AreaServiceID, &temp.AllowCallTime, &temp.Status)
if err != nil { if err != nil {
fmt.Println("GetPhone20Info SELECT:", i, err) fmt.Println("GetPhone20Info SELECT:", i, err)
......
package cache package cache
import ( import (
"dc_golang_server_1/dbmodel" "dc_golang_server_1/data_db_cache/dbdao"
"dc_golang_server_1/data_db_cache/model"
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
"fmt" "fmt"
"go.uber.org/zap" "go.uber.org/zap"
...@@ -14,9 +15,9 @@ func initWechatCustomerMap() { ...@@ -14,9 +15,9 @@ func initWechatCustomerMap() {
fmt.Println(time.Now(), "cache: initWechatCustomerMap begin") fmt.Println(time.Now(), "cache: initWechatCustomerMap begin")
var weUserID uint32 var weUserID uint32
var unionID string var unionID string
var temp WechatCustomerStruct var temp model.CacheUWeCustomerStruct
// 1. 查u_we_customer表获得基础数据 // 1. 查u_we_customer表获得基础数据
rows, err := dbmodel.PgDb.Query("SELECT id,unionid,phone,nickname,avatarurl,test_role FROM u_we_customer") // rows, err := dbdao.PgDb.Query("SELECT id,unionid,phone,nickname,avatarurl,test_role FROM u_we_customer") //
// defer rows.Close() // defer rows.Close()
if err != nil { if err != nil {
rows.Close() rows.Close()
...@@ -42,7 +43,7 @@ func initWechatCustomerMap() { ...@@ -42,7 +43,7 @@ func initWechatCustomerMap() {
rows.Close() rows.Close()
// 2. 查家长学生对应关系表u_we_card_user表,获得绑定的学生数据 // 2. 查家长学生对应关系表u_we_card_user表,获得绑定的学生数据
rows, err = dbmodel.PgDb.Query("SELECT we_user_id,card_user_id,master FROM u_we_card_user order by create_at") // rows, err = dbdao.PgDb.Query("SELECT we_user_id,card_user_id,master FROM u_we_card_user order by create_at") //
defer rows.Close() defer rows.Close()
if err != nil { if err != nil {
log.Panicln("Select u_we_card_user rows", err) log.Panicln("Select u_we_card_user rows", err)
...@@ -57,7 +58,7 @@ func initWechatCustomerMap() { ...@@ -57,7 +58,7 @@ func initWechatCustomerMap() {
} }
if master { if master {
if v, ok := WechatCustomerMap.Load(weUserID); ok { if v, ok := WechatCustomerMap.Load(weUserID); ok {
if value, ok := v.(WechatCustomerStruct); ok { if value, ok := v.(model.CacheUWeCustomerStruct); ok {
value.MasterCardUserID = append(value.MasterCardUserID, cUserID) value.MasterCardUserID = append(value.MasterCardUserID, cUserID)
WechatCustomerMap.Store(weUserID, value) WechatCustomerMap.Store(weUserID, value)
} else { } else {
...@@ -76,7 +77,7 @@ func initWechatCustomerMap() { ...@@ -76,7 +77,7 @@ func initWechatCustomerMap() {
} }
} else { } else {
if v, ok := WechatCustomerMap.Load(weUserID); ok { if v, ok := WechatCustomerMap.Load(weUserID); ok {
if value, ok := v.(WechatCustomerStruct); ok { if value, ok := v.(model.CacheUWeCustomerStruct); ok {
value.SlaveCardUserID = append(value.SlaveCardUserID, cUserID) value.SlaveCardUserID = append(value.SlaveCardUserID, cUserID)
WechatCustomerMap.Store(weUserID, value) WechatCustomerMap.Store(weUserID, value)
} else { } else {
...@@ -104,9 +105,9 @@ func initWechatCustomerMap() { ...@@ -104,9 +105,9 @@ func initWechatCustomerMap() {
} }
func GetWechatCustomerTokenCreatTime(weUserID uint32) int64 { func GetWechatCustomerTokenCreatTime(weUserID uint32) int64 {
var data WechatCustomerStruct var data model.CacheUWeCustomerStruct
if v, ok := WechatCustomerMap.Load(weUserID); ok { if v, ok := WechatCustomerMap.Load(weUserID); ok {
if data, ok = v.(WechatCustomerStruct); ok { if data, ok = v.(model.CacheUWeCustomerStruct); ok {
return data.TokenCreatTime //正常情况 return data.TokenCreatTime //正常情况
} else { } else {
logger.Log.Error("WechatCustomerMap 类型断言错误", logger.Log.Error("WechatCustomerMap 类型断言错误",
...@@ -123,9 +124,9 @@ func GetWechatCustomerTokenCreatTime(weUserID uint32) int64 { ...@@ -123,9 +124,9 @@ func GetWechatCustomerTokenCreatTime(weUserID uint32) int64 {
} }
func GetWechatCustomerTestRole(userID uint32) (bool, bool) { func GetWechatCustomerTestRole(userID uint32) (bool, bool) {
var data WechatCustomerStruct var data model.CacheUWeCustomerStruct
if v, ok := WechatCustomerMap.Load(userID); ok { if v, ok := WechatCustomerMap.Load(userID); ok {
if data, ok = v.(WechatCustomerStruct); ok { if data, ok = v.(model.CacheUWeCustomerStruct); ok {
return data.TestRole, true //正常情况 return data.TestRole, true //正常情况
} else { } else {
logger.Log.Error("WechatCustomerMap 类型断言错误", logger.Log.Error("WechatCustomerMap 类型断言错误",
...@@ -153,10 +154,10 @@ func GetWechatCustomerUserIDByUnionID(unionID string) uint32 { ...@@ -153,10 +154,10 @@ func GetWechatCustomerUserIDByUnionID(unionID string) uint32 {
return 0 return 0
} }
func GetWechatCustomerInfoAndCanUpdateTokenTime(weUserID uint32, newTime int64) (WechatCustomerStruct, bool) { func GetWechatCustomerInfoAndCanUpdateTokenTime(weUserID uint32, newTime int64) (model.CacheUWeCustomerStruct, bool) {
var data WechatCustomerStruct var data model.CacheUWeCustomerStruct
if v, ok := WechatCustomerMap.Load(weUserID); ok { if v, ok := WechatCustomerMap.Load(weUserID); ok {
if data, ok = v.(WechatCustomerStruct); ok { if data, ok = v.(model.CacheUWeCustomerStruct); ok {
if newTime != 0 { if newTime != 0 {
data.TokenCreatTime = newTime data.TokenCreatTime = newTime
WechatCustomerMap.Store(weUserID, data) WechatCustomerMap.Store(weUserID, data)
...@@ -181,12 +182,16 @@ func GetWechatCustomerInfoAndCanUpdateTokenTime(weUserID uint32, newTime int64) ...@@ -181,12 +182,16 @@ func GetWechatCustomerInfoAndCanUpdateTokenTime(weUserID uint32, newTime int64)
return data, false return data, false
} }
func InsertWechatCustomerMap(unionID string, userInfo *WechatCustomerStruct) uint32 { func InsertWechatCustomerMap(unionID string, userInfo *model.CacheUWeCustomerStruct) uint32 {
//id := dbdao.InsertUWeCustomerUnionID(unionID)
//if id == 0{
//
//}
var err error var err error
//var res sql.Result //var res sql.Result
var id uint32 var id uint32
for i := 0; i < 10; i++ { for i := 0; i < 10; i++ {
err = dbmodel.PgDb.QueryRow("INSERT INTO u_we_customer(unionid)VALUES($1)RETURNING id", unionID).Scan(&id) err = dbdao.PgDb.QueryRow("INSERT INTO u_we_customer(unionid)VALUES($1)RETURNING id", unionID).Scan(&id)
if err == nil { if err == nil {
WechatCustomerUnionIDToIDMAP.Store(unionID, id) WechatCustomerUnionIDToIDMAP.Store(unionID, id)
WechatCustomerMap.Store(id, *userInfo) WechatCustomerMap.Store(id, *userInfo)
...@@ -206,10 +211,10 @@ func InsertWechatCustomerMap(unionID string, userInfo *WechatCustomerStruct) uin ...@@ -206,10 +211,10 @@ func InsertWechatCustomerMap(unionID string, userInfo *WechatCustomerStruct) uin
return 0 return 0
} }
func selectDBWechatCustomerByUserIDToCache(userID uint32, userInfo *WechatCustomerStruct) bool { func selectDBWechatCustomerByUserIDToCache(userID uint32, userInfo *model.CacheUWeCustomerStruct) bool {
var unionID string var unionID string
// 1. 查u_we_customer表获得基础数据 // 1. 查u_we_customer表获得基础数据
err := dbmodel.PgDb.QueryRow("SELECT unionid,phone,nickname,avatarurl,test_role FROM u_we_customer WHERE id=$1", userID).Scan( err := dbdao.PgDb.QueryRow("SELECT unionid,phone,nickname,avatarurl,test_role FROM u_we_customer WHERE id=$1", userID).Scan(
&unionID, &unionID,
&userInfo.WePhone, &userInfo.WePhone,
&userInfo.Nickname, &userInfo.Nickname,
...@@ -222,7 +227,7 @@ func selectDBWechatCustomerByUserIDToCache(userID uint32, userInfo *WechatCustom ...@@ -222,7 +227,7 @@ func selectDBWechatCustomerByUserIDToCache(userID uint32, userInfo *WechatCustom
return false return false
} }
// 2. 查u_we_card_user表,获得绑定的学生数据 // 2. 查u_we_card_user表,获得绑定的学生数据
rows, err := dbmodel.PgDb.Query("SELECT card_user_id,master FROM u_we_card_user WHERE we_user_id=$1 order by create_at", userID) rows, err := dbdao.PgDb.Query("SELECT card_user_id,master FROM u_we_card_user WHERE we_user_id=$1 order by create_at", userID)
defer rows.Close() defer rows.Close()
if err != nil { if err != nil {
logger.Log.Error("selectDBWechatCustomerByUserIDToCache rows 错误", logger.Log.Error("selectDBWechatCustomerByUserIDToCache rows 错误",
...@@ -259,9 +264,9 @@ func selectDBWechatCustomerByUserIDToCache(userID uint32, userInfo *WechatCustom ...@@ -259,9 +264,9 @@ func selectDBWechatCustomerByUserIDToCache(userID uint32, userInfo *WechatCustom
return true return true
} }
func selectDBWechatCustomerByUnionIDToCache(unionID string, userInfo *WechatCustomerStruct) (userID uint32) { //返回userID func selectDBWechatCustomerByUnionIDToCache(unionID string, userInfo *model.CacheUWeCustomerStruct) (userID uint32) { //返回userID
// 1. 查u_we_customer表获得基础数据 // 1. 查u_we_customer表获得基础数据
err := dbmodel.PgDb.QueryRow("SELECT id,phone,nickname,avatarurl,test_role FROM u_we_customer WHERE unionid=$1", unionID).Scan( err := dbdao.PgDb.QueryRow("SELECT id,phone,nickname,avatarurl,test_role FROM u_we_customer WHERE unionid=$1", unionID).Scan(
&userID, &userID,
&userInfo.WePhone, &userInfo.WePhone,
&userInfo.Nickname, &userInfo.Nickname,
...@@ -274,7 +279,7 @@ func selectDBWechatCustomerByUnionIDToCache(unionID string, userInfo *WechatCust ...@@ -274,7 +279,7 @@ func selectDBWechatCustomerByUnionIDToCache(unionID string, userInfo *WechatCust
return return
} }
// 2. 查u_we_card_user表,获得绑定的学生数据 // 2. 查u_we_card_user表,获得绑定的学生数据
rows, err := dbmodel.PgDb.Query("SELECT card_user_id,master FROM u_we_card_user WHERE we_user_id=$1 order by create_at", userID) rows, err := dbdao.PgDb.Query("SELECT card_user_id,master FROM u_we_card_user WHERE we_user_id=$1 order by create_at", userID)
defer rows.Close() defer rows.Close()
if err != nil { if err != nil {
logger.Log.Error("selectDBWechatCustomerByUnionIDToCache rows 错误", logger.Log.Error("selectDBWechatCustomerByUnionIDToCache rows 错误",
...@@ -314,9 +319,9 @@ func selectDBWechatCustomerByUnionIDToCache(unionID string, userInfo *WechatCust ...@@ -314,9 +319,9 @@ func selectDBWechatCustomerByUnionIDToCache(unionID string, userInfo *WechatCust
// InsertNewStudentIDToWechatCustomerMap 缓存定制方法:微信用户增加/绑定卡用户 // InsertNewStudentIDToWechatCustomerMap 缓存定制方法:微信用户增加/绑定卡用户
func InsertNewStudentIDToWechatCustomerMap(weUserID uint32, cardUserID uint32, master bool) bool { func InsertNewStudentIDToWechatCustomerMap(weUserID uint32, cardUserID uint32, master bool) bool {
var data WechatCustomerStruct var data model.CacheUWeCustomerStruct
if v, ok := WechatCustomerMap.Load(weUserID); ok { if v, ok := WechatCustomerMap.Load(weUserID); ok {
if data, ok = v.(WechatCustomerStruct); ok { if data, ok = v.(model.CacheUWeCustomerStruct); ok {
if master { if master {
data.MasterCardUserID = append(data.MasterCardUserID, cardUserID) data.MasterCardUserID = append(data.MasterCardUserID, cardUserID)
} else { } else {
......
package dbmodel package dbdao
//CREATE TABLE IF NOT EXISTS public.d_device //CREATE TABLE IF NOT EXISTS public.d_device
//( //(
......
package dbmodel package dbdao
import ( import (
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
......
package dbmodel package dbdao
import ( import (
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
......
package dbmodel package dbdao
import ( import (
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
......
package dbmodel package dbdao
import ( import (
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
......
package dbmodel package dbdao
import ( import (
"database/sql" "database/sql"
"dc_golang_server_1/config" config2 "dc_golang_server_1/util/config"
_ "github.com/lib/pq" _ "github.com/lib/pq"
) )
...@@ -17,7 +17,7 @@ var stmtInsertDevHexResetRecord *sql.Stmt ...@@ -17,7 +17,7 @@ var stmtInsertDevHexResetRecord *sql.Stmt
func InitDb() { func InitDb() {
var err error var err error
// fmt.Println("DBDSN",config.DbDSN) // fmt.Println("DBDSN",config.DbDSN)
PgDb, err = sql.Open("postgres", config.DbDSN) PgDb, err = sql.Open("postgres", config2.DbDSN)
if err != nil { if err != nil {
panic("数据库连接失败" + err.Error()) panic("数据库连接失败" + err.Error())
} }
......
package dbmodel package dbdao
import ( import (
"database/sql" "database/sql"
......
package dbmodel package dbdao
import ( import (
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
......
package dbmodel package dbdao
import ( import (
"time" "time"
......
package dbmodel package dbdao
//CREATE TABLE IF NOT EXISTS public.u_sim_info //CREATE TABLE IF NOT EXISTS public.u_sim_info
//( //(
......
package devproduct package devproduct
import ( import (
"dc_golang_server_1/dbmodel" "dc_golang_server_1/data_db_cache/dbdao"
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
"dc_golang_server_1/util" "dc_golang_server_1/util"
"encoding/hex" "encoding/hex"
...@@ -37,7 +37,7 @@ type HexData struct { ...@@ -37,7 +37,7 @@ type HexData struct {
} }
func /*(d *DCLongTCPHex)*/ insertDevHexCommandRecord(data *HexData, ciphertext string, direction uint8) { func /*(d *DCLongTCPHex)*/ insertDevHexCommandRecord(data *HexData, ciphertext string, direction uint8) {
go dbmodel.InsertDevCommandRecord(dbmodel.TableDevHexCommandRecord{ go dbdao.InsertDevCommandRecord(dbdao.TableDevHexCommandRecord{
DevID: data.DevID, DevID: data.DevID,
DevUtc: data.TimeUtc, DevUtc: data.TimeUtc,
CtrlCode: strconv.FormatUint(uint64(data.CtrlCode), 16), CtrlCode: strconv.FormatUint(uint64(data.CtrlCode), 16),
...@@ -52,20 +52,20 @@ func (d *DCLongTCPHex) receiveResponse(conn *net.TCPConn, data []byte, nowConnDe ...@@ -52,20 +52,20 @@ func (d *DCLongTCPHex) receiveResponse(conn *net.TCPConn, data []byte, nowConnDe
c, err := util.DecryptBase64ToBytes(data, d.password, d.iv) c, err := util.DecryptBase64ToBytes(data, d.password, d.iv)
if err != nil { if err != nil {
if nowConnDevID != 0 { if nowConnDevID != 0 {
dbmodel.InsertDevCommandErr(nowConnDevID, string(data), "Decrypt err") dbdao.InsertDevCommandErr(nowConnDevID, string(data), "Decrypt err")
} }
return 0 return 0
} }
if util.CheckCRC(c) == false { if util.CheckCRC(c) == false {
dbmodel.InsertDevCommandErr(nowConnDevID, string(data), "CheckCRC err") dbdao.InsertDevCommandErr(nowConnDevID, string(data), "CheckCRC err")
return 0 return 0
} }
cLen := len(c) cLen := len(c)
if cLen < 12 { if cLen < 12 {
dbmodel.InsertDevCommandErr(nowConnDevID, string(data), "cLen<12") dbdao.InsertDevCommandErr(nowConnDevID, string(data), "cLen<12")
return 0 return 0
} else if int(c[9])+12 != cLen { } else if int(c[9])+12 != cLen {
dbmodel.InsertDevCommandErr(nowConnDevID, string(data), "cLen!=c[9]+12") dbdao.InsertDevCommandErr(nowConnDevID, string(data), "cLen!=c[9]+12")
return 0 return 0
} }
...@@ -75,13 +75,13 @@ func (d *DCLongTCPHex) receiveResponse(conn *net.TCPConn, data []byte, nowConnDe ...@@ -75,13 +75,13 @@ func (d *DCLongTCPHex) receiveResponse(conn *net.TCPConn, data []byte, nowConnDe
// 时间有效性判断 // 时间有效性判断
nowTimeUtc := uint32(time.Now().Unix()) nowTimeUtc := uint32(time.Now().Unix())
if nowTimeUtc > rData.TimeUtc+300 || rData.TimeUtc > nowTimeUtc+300 { if nowTimeUtc > rData.TimeUtc+300 || rData.TimeUtc > nowTimeUtc+300 {
dbmodel.InsertDevCommandErr(nowConnDevID, string(data), "utc err:"+strconv.FormatUint(uint64(rData.TimeUtc), 10)) dbdao.InsertDevCommandErr(nowConnDevID, string(data), "utc err:"+strconv.FormatUint(uint64(rData.TimeUtc), 10))
return 0 return 0
} }
// 设备类型判断 // 设备类型判断
if c[4] != d.devType { if c[4] != d.devType {
dbmodel.InsertDevCommandErr(nowConnDevID, string(data), "devType error") dbdao.InsertDevCommandErr(nowConnDevID, string(data), "devType error")
return 0 return 0
} }
......
package dcphone20 package dcphone20
import ( import (
"dc_golang_server_1/config" config2 "dc_golang_server_1/util/config"
) )
func NewDCPhone20() { func NewDCPhone20() {
var dcPhone20TCP DCPhone20 var dcPhone20TCP DCPhone20
dcPhone20TCP.NewDCPhone20("DCRYM-2018-pswd.", "I can't tell YOU", 0x5B) // config dcPhone20TCP.NewDCPhone20("DCRYM-2018-pswd.", "I can't tell YOU", 0x5B) // config
dcPhone20TCP.TCPStart(config.TcpLongPort) dcPhone20TCP.TCPStart(config2.TcpLongPort)
// dcPhone10TCP.NewDCPhone20API(r) // dcPhone10TCP.NewDCPhone20API(r)
} }
package dcphone20 package dcphone20
import ( import (
"dc_golang_server_1/cache" "dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/dbmodel" "dc_golang_server_1/data_db_cache/dbdao"
"dc_golang_server_1/devproduct" "dc_golang_server_1/devproduct"
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
"fmt" "fmt"
...@@ -493,7 +493,7 @@ func (dev *DCPhone20) response(data *devproduct.HexData) { ...@@ -493,7 +493,7 @@ func (dev *DCPhone20) response(data *devproduct.HexData) {
case 0x26: // 0x22:"usedevice/dev_post_call_log",// 上报通话记录 SIM ICCID case 0x26: // 0x22:"usedevice/dev_post_call_log",// 上报通话记录 SIM ICCID
if data.Length > 27 { //todo if data.Length > 27 { //todo
//devInfo := cache.GetDeviceInfo(data.DevID) //devInfo := cache.GetDeviceInfo(data.DevID)
//var areaInfo cache.AreaStruct //var areaInfo cache.CacheBAreaStruct
//if devInfo.AreaID > 0 { //if devInfo.AreaID > 0 {
// areaInfo = cache.GetAreaInfo(devInfo.AreaID) // areaInfo = cache.GetAreaInfo(devInfo.AreaID)
//} //}
...@@ -507,7 +507,7 @@ func (dev *DCPhone20) response(data *devproduct.HexData) { ...@@ -507,7 +507,7 @@ func (dev *DCPhone20) response(data *devproduct.HexData) {
// } // }
//} //}
//// 以事务方式存2张表 //// 以事务方式存2张表
//if result := dbmodel.InsertUCallRecordAndUpdateUSimInfo(dbmodel.TableUserCallRecord{ //if result := dbdao.InsertUCallRecordAndUpdateUSimInfo(dbdao.TableUserCallRecord{
// //CustomerId: // //CustomerId:
// //CardUserId: // //CardUserId:
// //CardUserName: // //CardUserName:
...@@ -595,7 +595,7 @@ func insertDevHexResetRecord(data *devproduct.HexData) { ...@@ -595,7 +595,7 @@ func insertDevHexResetRecord(data *devproduct.HexData) {
} }
firmwareVersion = strTemp[2] // firmwareVersion = strTemp[2] //
} }
go dbmodel.InsertDevResetRecord(dbmodel.TableDevHexResetRecord{ go dbdao.InsertDevResetRecord(dbdao.TableDevHexResetRecord{
DevId: data.DevID, DevId: data.DevID,
DevUtc: data.TimeUtc, DevUtc: data.TimeUtc,
ResetReason: resetReason, ResetReason: resetReason,
......
package devproduct package devproduct
import ( import (
"dc_golang_server_1/config" "dc_golang_server_1/data_db_cache/dbdao"
"dc_golang_server_1/dbmodel"
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
config2 "dc_golang_server_1/util/config"
"go.uber.org/zap" "go.uber.org/zap"
"net" "net"
"strconv" "strconv"
...@@ -93,7 +93,7 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall ...@@ -93,7 +93,7 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall
if co, ok := connMyID.(*net.TCPConn); ok { // 类型断言 if co, ok := connMyID.(*net.TCPConn); ok { // 类型断言
if co == conn { if co == conn {
s.ConnectMap.Delete(myDevID) s.ConnectMap.Delete(myDevID)
dbmodel.DevConnectRecord(myDevID, 1) // state 0:新连接来了 1:设备正常离线 2:正常离线 3:新连接挤掉就连接 4:未知异常(连接池类型断言失败) dbdao.DevConnectRecord(myDevID, 1) // state 0:新连接来了 1:设备正常离线 2:正常离线 3:新连接挤掉就连接 4:未知异常(连接池类型断言失败)
//logger.Log.Debug("device offline", //logger.Log.Debug("device offline",
// zap.String("Src", "TCP-SERVER-connectionHandle"), // zap.String("Src", "TCP-SERVER-connectionHandle"),
// zap.Uint32("DevID", myDevID), // zap.Uint32("DevID", myDevID),
...@@ -101,7 +101,7 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall ...@@ -101,7 +101,7 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall
// zap.String("State", "offline")) // zap.String("State", "offline"))
} else { } else {
// s.ConnectMap.Delete(myDevID) 这里人家存了新的,不能去删了噻 // s.ConnectMap.Delete(myDevID) 这里人家存了新的,不能去删了噻
dbmodel.DevConnectRecord(myDevID, 3) // state 0:新连接来了 1:设备正常离线 2:正常离线 3:新连接挤掉就连接 4:未知异常(连接池类型断言失败) dbdao.DevConnectRecord(myDevID, 3) // state 0:新连接来了 1:设备正常离线 2:正常离线 3:新连接挤掉就连接 4:未知异常(连接池类型断言失败)
//logger.Log.Debug("have a new link,close old link", //logger.Log.Debug("have a new link,close old link",
// zap.String("Src", "TCP-SERVER-connectionHandle"), // zap.String("Src", "TCP-SERVER-connectionHandle"),
// zap.Uint32("DevID", myDevID), // zap.Uint32("DevID", myDevID),
...@@ -115,7 +115,7 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall ...@@ -115,7 +115,7 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall
// zap.Uint32("DevID", myDevID), // zap.Uint32("DevID", myDevID),
// zap.String("Conn", conn.RemoteAddr().String()), // zap.String("Conn", conn.RemoteAddr().String()),
// zap.String("State", "offline")) // 类型断言失败 // zap.String("State", "offline")) // 类型断言失败
dbmodel.DevConnectRecord(myDevID, 4) // state 0:新连接来了 1:设备正常离线 2:正常离线 3:新连接挤掉就连接 4:未知异常(连接池类型断言失败) dbdao.DevConnectRecord(myDevID, 4) // state 0:新连接来了 1:设备正常离线 2:正常离线 3:新连接挤掉就连接 4:未知异常(连接池类型断言失败)
} }
} else { } else {
//logger.Log.Debug("map no have myDevID", //logger.Log.Debug("map no have myDevID",
...@@ -123,7 +123,7 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall ...@@ -123,7 +123,7 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall
// zap.Uint32("DevID", myDevID), // zap.Uint32("DevID", myDevID),
// zap.String("Conn", conn.RemoteAddr().String()), // zap.String("Conn", conn.RemoteAddr().String()),
// zap.String("State", "offline")) // zap.String("State", "offline"))
dbmodel.DevConnectRecord(myDevID, 2) // state 0:新连接来了 1:设备正常离线 2:正常离线 3:新连接挤掉就连接 4:未知异常(连接池类型断言失败) dbdao.DevConnectRecord(myDevID, 2) // state 0:新连接来了 1:设备正常离线 2:正常离线 3:新连接挤掉就连接 4:未知异常(连接池类型断言失败)
} }
} }
...@@ -132,8 +132,8 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall ...@@ -132,8 +132,8 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall
// fmt.Println("-----------------------------------Out ConnSocketCount:", s.ConnSocketCount) // fmt.Println("-----------------------------------Out ConnSocketCount:", s.ConnSocketCount)
}() }()
if s.ConnSocketCount > config.TcpLongMaxConnections { //限制最大连接数2万个配置文件 最大连接限制数添加到配置文件 if s.ConnSocketCount > config2.TcpLongMaxConnections { //限制最大连接数2万个配置文件 最大连接限制数添加到配置文件
logger.Log.Error("ConnSocketCount overrun:"+strconv.Itoa(int(config.TcpLongMaxConnections)), logger.Log.Error("ConnSocketCount overrun:"+strconv.Itoa(int(config2.TcpLongMaxConnections)),
zap.String("Src", "TCP-SERVER-connectionHandle"), zap.String("Src", "TCP-SERVER-connectionHandle"),
zap.Uint32("DevID", myDevID), zap.Uint32("DevID", myDevID),
zap.String("Conn", conn.RemoteAddr().String()), zap.String("Conn", conn.RemoteAddr().String()),
...@@ -146,18 +146,18 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall ...@@ -146,18 +146,18 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall
rBuf := make([]byte, 512) rBuf := make([]byte, 512)
rLen := 0 rLen := 0
i := 0 i := 0
timeConn := time.Now().Unix() + config.TcpLongNewConnRightfulTimeout //配置文件 120秒 timeConn := time.Now().Unix() + config2.TcpLongNewConnRightfulTimeout //配置文件 120秒
for { for {
if myDevID == 0 { if myDevID == 0 {
if time.Now().Unix() > timeConn { // 连上来2分钟都没整个正确的数据来,就给它断球 if time.Now().Unix() > timeConn { // 连上来2分钟都没整个正确的数据来,就给它断球
logger.Log.Warn("NewConnRightfulTimeout:"+strconv.Itoa(int(config.TcpLongNewConnRightfulTimeout)), // 超时没收到合法的指令 logger.Log.Warn("NewConnRightfulTimeout:"+strconv.Itoa(int(config2.TcpLongNewConnRightfulTimeout)), // 超时没收到合法的指令
zap.String("Src", "TCP-SERVER-connectionHandle"), zap.String("Src", "TCP-SERVER-connectionHandle"),
// zap.Uint32("DevID", myDevID), // zap.Uint32("DevID", myDevID),
zap.String("Conn", conn.RemoteAddr().String()), zap.String("Conn", conn.RemoteAddr().String()),
zap.Int32("ConnSocketCount", s.ConnSocketCount)) zap.Int32("ConnSocketCount", s.ConnSocketCount))
return return
} }
if err := conn.SetReadDeadline(time.Now().Add(config.TcpLongNewConnReadDeadline)); err != nil { // 配置文件 新连接1分钟超时未收到数据(配置文件用秒) if err := conn.SetReadDeadline(time.Now().Add(config2.TcpLongNewConnReadDeadline)); err != nil { // 配置文件 新连接1分钟超时未收到数据(配置文件用秒)
logger.Log.Warn("conn.SetReadDeadline:new", // logger.Log.Warn("conn.SetReadDeadline:new", //
zap.String("Src", "TCP-SERVER-connectionHandle"), zap.String("Src", "TCP-SERVER-connectionHandle"),
zap.Uint32("DevID", myDevID), zap.Uint32("DevID", myDevID),
...@@ -167,7 +167,7 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall ...@@ -167,7 +167,7 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall
return return
} }
} else { } else {
if err := conn.SetReadDeadline(time.Now().Add(config.TcpLongOldConnReadDeadline)); err != nil { // 配置文件 老连接3分钟超时未收到数据(配置文件用秒) if err := conn.SetReadDeadline(time.Now().Add(config2.TcpLongOldConnReadDeadline)); err != nil { // 配置文件 老连接3分钟超时未收到数据(配置文件用秒)
logger.Log.Warn("conn.SetReadDeadline:old", // logger.Log.Warn("conn.SetReadDeadline:old", //
zap.String("Src", "TCP-SERVER-connectionHandle"), zap.String("Src", "TCP-SERVER-connectionHandle"),
zap.Uint32("DevID", myDevID), zap.Uint32("DevID", myDevID),
...@@ -221,7 +221,7 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall ...@@ -221,7 +221,7 @@ func (s *TCPLongServer) connectionHandle(conn *net.TCPConn, callBack receiveCall
}*/ }*/
} }
// logger 新链接来的合法设备 // logger 新链接来的合法设备
dbmodel.DevConnectRecord(newID, 0) dbdao.DevConnectRecord(newID, 0)
//logger.Log.Debug("a new link is coming", //logger.Log.Debug("a new link is coming",
// zap.String("Src", "TCP-SERVER-connectionHandle"), // zap.String("Src", "TCP-SERVER-connectionHandle"),
// zap.Uint32("DevID", newID), // zap.Uint32("DevID", newID),
......
...@@ -48,7 +48,7 @@ var doc = `{ ...@@ -48,7 +48,7 @@ var doc = `{
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dbmodel.TableBaseArea" "$ref": "#/definitions/dbdao.TableBaseArea"
} }
} }
], ],
...@@ -89,7 +89,7 @@ var doc = `{ ...@@ -89,7 +89,7 @@ var doc = `{
"schema": { "schema": {
"type": "array", "type": "array",
"items": { "items": {
"$ref": "#/definitions/cache.DistrictStruct" "$ref": "#/definitions/model.CacheBDistrictStruct"
} }
} }
} }
...@@ -123,7 +123,7 @@ var doc = `{ ...@@ -123,7 +123,7 @@ var doc = `{
"schema": { "schema": {
"type": "array", "type": "array",
"items": { "items": {
"$ref": "#/definitions/cache.DistrictStruct" "$ref": "#/definitions/model.CacheBDistrictStruct"
} }
} }
} }
...@@ -226,7 +226,7 @@ var doc = `{ ...@@ -226,7 +226,7 @@ var doc = `{
"schema": { "schema": {
"type": "array", "type": "array",
"items": { "items": {
"$ref": "#/definitions/cache.DistrictStruct" "$ref": "#/definitions/model.CacheBDistrictStruct"
} }
} }
} }
...@@ -560,7 +560,7 @@ var doc = `{ ...@@ -560,7 +560,7 @@ var doc = `{
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dbmodel.InsertTableUserCardUser" "$ref": "#/definitions/dbdao.InsertTableUserCardUser"
} }
} }
], ],
...@@ -1339,24 +1339,7 @@ var doc = `{ ...@@ -1339,24 +1339,7 @@ var doc = `{
} }
} }
}, },
"cache.DistrictStruct": { "dbdao.InsertTableUserCardUser": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"initial": {
"type": "string",
"example": "S"
},
"name": {
"type": "string",
"example": "四川省"
}
}
},
"dbmodel.InsertTableUserCardUser": {
"type": "object", "type": "object",
"properties": { "properties": {
"areaID": { "areaID": {
...@@ -1387,7 +1370,7 @@ var doc = `{ ...@@ -1387,7 +1370,7 @@ var doc = `{
} }
} }
}, },
"dbmodel.TableBaseArea": { "dbdao.TableBaseArea": {
"type": "object", "type": "object",
"properties": { "properties": {
"county_id": { "county_id": {
...@@ -1421,6 +1404,23 @@ var doc = `{ ...@@ -1421,6 +1404,23 @@ var doc = `{
"example": 1 "example": 1
} }
} }
},
"model.CacheBDistrictStruct": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"initial": {
"type": "string",
"example": "S"
},
"name": {
"type": "string",
"example": "四川省"
}
}
} }
}, },
"securityDefinitions": { "securityDefinitions": {
...@@ -1443,7 +1443,7 @@ type swaggerInfo struct { ...@@ -1443,7 +1443,7 @@ type swaggerInfo struct {
// SwaggerInfo holds exported Swagger Info so clients can modify it // SwaggerInfo holds exported Swagger Info so clients can modify it
var SwaggerInfo = swaggerInfo{ var SwaggerInfo = swaggerInfo{
Version: "V0.0.1", Version: "V0.0.0.1",
Host: "", Host: "",
BasePath: "/", BasePath: "/",
Schemes: []string{}, Schemes: []string{},
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
"description": "用于家长端微信小程序及web端管理后台", "description": "用于家长端微信小程序及web端管理后台",
"title": "多彩中小学一卡通系统", "title": "多彩中小学一卡通系统",
"contact": {}, "contact": {},
"version": "V0.0.1" "version": "V0.0.0.1"
}, },
"basePath": "/", "basePath": "/",
"paths": { "paths": {
...@@ -33,7 +33,7 @@ ...@@ -33,7 +33,7 @@
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dbmodel.TableBaseArea" "$ref": "#/definitions/dbdao.TableBaseArea"
} }
} }
], ],
...@@ -74,7 +74,7 @@ ...@@ -74,7 +74,7 @@
"schema": { "schema": {
"type": "array", "type": "array",
"items": { "items": {
"$ref": "#/definitions/cache.DistrictStruct" "$ref": "#/definitions/model.CacheBDistrictStruct"
} }
} }
} }
...@@ -108,7 +108,7 @@ ...@@ -108,7 +108,7 @@
"schema": { "schema": {
"type": "array", "type": "array",
"items": { "items": {
"$ref": "#/definitions/cache.DistrictStruct" "$ref": "#/definitions/model.CacheBDistrictStruct"
} }
} }
} }
...@@ -211,7 +211,7 @@ ...@@ -211,7 +211,7 @@
"schema": { "schema": {
"type": "array", "type": "array",
"items": { "items": {
"$ref": "#/definitions/cache.DistrictStruct" "$ref": "#/definitions/model.CacheBDistrictStruct"
} }
} }
} }
...@@ -545,7 +545,7 @@ ...@@ -545,7 +545,7 @@
"in": "body", "in": "body",
"required": true, "required": true,
"schema": { "schema": {
"$ref": "#/definitions/dbmodel.InsertTableUserCardUser" "$ref": "#/definitions/dbdao.InsertTableUserCardUser"
} }
} }
], ],
...@@ -1324,24 +1324,7 @@ ...@@ -1324,24 +1324,7 @@
} }
} }
}, },
"cache.DistrictStruct": { "dbdao.InsertTableUserCardUser": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"initial": {
"type": "string",
"example": "S"
},
"name": {
"type": "string",
"example": "四川省"
}
}
},
"dbmodel.InsertTableUserCardUser": {
"type": "object", "type": "object",
"properties": { "properties": {
"areaID": { "areaID": {
...@@ -1372,7 +1355,7 @@ ...@@ -1372,7 +1355,7 @@
} }
} }
}, },
"dbmodel.TableBaseArea": { "dbdao.TableBaseArea": {
"type": "object", "type": "object",
"properties": { "properties": {
"county_id": { "county_id": {
...@@ -1406,6 +1389,23 @@ ...@@ -1406,6 +1389,23 @@
"example": 1 "example": 1
} }
} }
},
"model.CacheBDistrictStruct": {
"type": "object",
"properties": {
"id": {
"type": "integer",
"example": 1
},
"initial": {
"type": "string",
"example": "S"
},
"name": {
"type": "string",
"example": "四川省"
}
}
} }
}, },
"securityDefinitions": { "securityDefinitions": {
......
...@@ -283,19 +283,7 @@ definitions: ...@@ -283,19 +283,7 @@ definitions:
description: 显示在第一行 description: 显示在第一行
type: string type: string
type: object type: object
cache.DistrictStruct: dbdao.InsertTableUserCardUser:
properties:
id:
example: 1
type: integer
initial:
example: S
type: string
name:
example: 四川省
type: string
type: object
dbmodel.InsertTableUserCardUser:
properties: properties:
areaID: areaID:
description: 必填,校区ID description: 必填,校区ID
...@@ -318,7 +306,7 @@ definitions: ...@@ -318,7 +306,7 @@ definitions:
description: 选填,学号,字符串,maxLen=32 description: 选填,学号,字符串,maxLen=32
type: string type: string
type: object type: object
dbmodel.TableBaseArea: dbdao.TableBaseArea:
properties: properties:
county_id: county_id:
description: 必填,所属区县ID description: 必填,所属区县ID
...@@ -345,11 +333,23 @@ definitions: ...@@ -345,11 +333,23 @@ definitions:
example: 1 example: 1
type: integer type: integer
type: object type: object
model.CacheBDistrictStruct:
properties:
id:
example: 1
type: integer
initial:
example: S
type: string
name:
example: 四川省
type: string
type: object
info: info:
contact: {} contact: {}
description: 用于家长端微信小程序及web端管理后台 description: 用于家长端微信小程序及web端管理后台
title: 多彩中小学一卡通系统 title: 多彩中小学一卡通系统
version: V0.0.1 version: V0.0.0.1
paths: paths:
/ad/area: /ad/area:
post: post:
...@@ -362,7 +362,7 @@ paths: ...@@ -362,7 +362,7 @@ paths:
name: data name: data
required: true required: true
schema: schema:
$ref: '#/definitions/dbmodel.TableBaseArea' $ref: '#/definitions/dbdao.TableBaseArea'
produces: produces:
- application/json - application/json
responses: responses:
...@@ -389,7 +389,7 @@ paths: ...@@ -389,7 +389,7 @@ paths:
description: 按首字母排序好的列表,可直接用作展示 description: 按首字母排序好的列表,可直接用作展示
schema: schema:
items: items:
$ref: '#/definitions/cache.DistrictStruct' $ref: '#/definitions/model.CacheBDistrictStruct'
type: array type: array
security: security:
- ApiKeyAuth: [] - ApiKeyAuth: []
...@@ -410,7 +410,7 @@ paths: ...@@ -410,7 +410,7 @@ paths:
description: 按首字母排序好的列表,可直接用作展示 description: 按首字母排序好的列表,可直接用作展示
schema: schema:
items: items:
$ref: '#/definitions/cache.DistrictStruct' $ref: '#/definitions/model.CacheBDistrictStruct'
type: array type: array
security: security:
- ApiKeyAuth: [] - ApiKeyAuth: []
...@@ -475,7 +475,7 @@ paths: ...@@ -475,7 +475,7 @@ paths:
description: 按首字母排序好的列表,可直接用作展示 description: 按首字母排序好的列表,可直接用作展示
schema: schema:
items: items:
$ref: '#/definitions/cache.DistrictStruct' $ref: '#/definitions/model.CacheBDistrictStruct'
type: array type: array
security: security:
- ApiKeyAuth: [] - ApiKeyAuth: []
...@@ -686,7 +686,7 @@ paths: ...@@ -686,7 +686,7 @@ paths:
name: data name: data
required: true required: true
schema: schema:
$ref: '#/definitions/dbmodel.InsertTableUserCardUser' $ref: '#/definitions/dbdao.InsertTableUserCardUser'
produces: produces:
- application/json - application/json
responses: responses:
......
package logger package logger
import ( import (
config2 "dc_golang_server_1/config" config3 "dc_golang_server_1/util/config"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/natefinch/lumberjack" "github.com/natefinch/lumberjack"
"go.uber.org/zap" "go.uber.org/zap"
...@@ -30,38 +30,38 @@ func Init() { ...@@ -30,38 +30,38 @@ func Init() {
//debug info //debug info
infoLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { infoLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl < zapcore.WarnLevel && lvl >= config2.LogLevel return lvl < zapcore.WarnLevel && lvl >= config3.LogLevel
}) })
//warn //warn
warnLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { warnLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl == zapcore.WarnLevel && lvl >= config2.LogLevel return lvl == zapcore.WarnLevel && lvl >= config3.LogLevel
}) })
//error DPanic Panci Fatal //error DPanic Panci Fatal
errorLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool { errorLevel := zap.LevelEnablerFunc(func(lvl zapcore.Level) bool {
return lvl > zapcore.WarnLevel && lvl >= config2.LogLevel return lvl > zapcore.WarnLevel && lvl >= config3.LogLevel
}) })
infoWriter := &lumberjack.Logger{ infoWriter := &lumberjack.Logger{
Filename: config2.LogPath + "info.log", Filename: config3.LogPath + "info.log",
MaxSize: config2.LogFileMaxSize, //最大M数,超过则切割 MaxSize: config3.LogFileMaxSize, //最大M数,超过则切割
MaxBackups: config2.LogInfoMaxFileNum, //最大文件保留数,超过就删除最老的日志文件 MaxBackups: config3.LogInfoMaxFileNum, //最大文件保留数,超过就删除最老的日志文件
MaxAge: config2.LogInfoMaxFileDay, //保存30天 MaxAge: config3.LogInfoMaxFileDay, //保存30天
Compress: false, //是否压缩 Compress: false, //是否压缩
} }
warnWriter := &lumberjack.Logger{ warnWriter := &lumberjack.Logger{
Filename: config2.LogPath + "warn.log", Filename: config3.LogPath + "warn.log",
MaxSize: config2.LogFileMaxSize, //最大M数,超过则切割 MaxSize: config3.LogFileMaxSize, //最大M数,超过则切割
MaxBackups: config2.LogWarnMaxFileNum, //最大文件保留数,超过就删除最老的日志文件 MaxBackups: config3.LogWarnMaxFileNum, //最大文件保留数,超过就删除最老的日志文件
MaxAge: config2.LogWarnMaxFileDay, //保存30天 MaxAge: config3.LogWarnMaxFileDay, //保存30天
Compress: false, //是否压缩 Compress: false, //是否压缩
} }
errorWriter := &lumberjack.Logger{ errorWriter := &lumberjack.Logger{
Filename: config2.LogPath + "error.log", Filename: config3.LogPath + "error.log",
MaxSize: config2.LogFileMaxSize, //最大M数,超过则切割 MaxSize: config3.LogFileMaxSize, //最大M数,超过则切割
MaxBackups: config2.LogErrorMaxFileNum, //最大文件保留数,超过就删除最老的日志文件 MaxBackups: config3.LogErrorMaxFileNum, //最大文件保留数,超过就删除最老的日志文件
MaxAge: config2.LogErrorMaxFileDay, //保存30天 MaxAge: config3.LogErrorMaxFileDay, //保存30天
Compress: false, //是否压缩 Compress: false, //是否压缩
} }
...@@ -76,11 +76,6 @@ func Init() { ...@@ -76,11 +76,6 @@ func Init() {
func HttpGinLog() gin.HandlerFunc { //logger *log.Log func HttpGinLog() gin.HandlerFunc { //logger *log.Log
return func(c *gin.Context) { return func(c *gin.Context) {
//defer func() {
// if r := recover();r!=nil{
// fmt.Println("recover",r)
// }
//}()
startTime := time.Now().UnixMicro() startTime := time.Now().UnixMicro()
c.Next() c.Next()
// stopTime := time.Since(startTime) // stopTime := time.Since(startTime)
......
package main package main
import ( import (
"dc_golang_server_1/cache" "dc_golang_server_1/api/router"
"dc_golang_server_1/config" "dc_golang_server_1/data_db_cache/cache"
"dc_golang_server_1/dbmodel" "dc_golang_server_1/data_db_cache/dbdao"
"dc_golang_server_1/devproduct/dcphone20" "dc_golang_server_1/devproduct/dcphone20"
"dc_golang_server_1/logger" "dc_golang_server_1/logger"
"dc_golang_server_1/web/router" config2 "dc_golang_server_1/util/config"
"fmt" "fmt"
"os" "os"
"os/signal" "os/signal"
...@@ -16,7 +16,7 @@ import ( ...@@ -16,7 +16,7 @@ import (
) )
// @title 多彩中小学一卡通系统 // @title 多彩中小学一卡通系统
// @version V0.0.1 // @version V0.0.0.1
// @Description 用于家长端微信小程序及web端管理后台 // @Description 用于家长端微信小程序及web端管理后台
// @securityDefinitions.apikey ApiKeyAuth // @securityDefinitions.apikey ApiKeyAuth
// @in header // @in header
...@@ -26,20 +26,20 @@ func main() { // ...@@ -26,20 +26,20 @@ func main() { //
fmt.Println(time.Now(), "system init") fmt.Println(time.Now(), "system init")
runtime.GOMAXPROCS(runtime.NumCPU()) runtime.GOMAXPROCS(runtime.NumCPU())
config.Init() config2.Init()
logger.Init() logger.Init()
go func() { go func() {
osc := make(chan os.Signal, 1) osc := make(chan os.Signal, 1)
signal.Notify(osc, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL) signal.Notify(osc, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)
s := <-osc s := <-osc
dbmodel.CloseDb() dbdao.CloseDb()
fmt.Println("程序退出:", s) fmt.Println("程序退出:", s)
os.Exit(1) os.Exit(1)
}() }()
dbmodel.InitDb() dbdao.InitDb()
// defer dbmodel.CloseDb() // defer dbdao.CloseDb()
cache.Init() cache.Init()
......
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