作者 唐旭辉

新建

package common
import (
"oppmg/common/config"
"oppmg/common/log"
"github.com/astaxie/beego"
)
func ResetCommonConfig() {
mconfig := config.RestMyConfig()
var setlog log.SetLoggerConfig
if mconfig.LogOutput == "console" {
setlog = &log.LoggerConsole{
Level: log.LogLevelDebug, Color: true,
}
} else if mconfig.LogOutput == "file" {
setlog = &log.LoggerFile{
Level: log.LogLevel(mconfig.LogLevel),
FileName: mconfig.LogFilename,
}
}
var logCallfunc bool
if beego.BConfig.RunMode != "prod" {
logCallfunc = true
}
log.ResetLog(setlog, logCallfunc)
}
... ...
package config
import (
"github.com/astaxie/beego"
)
//MyConfig 自定义配置选项
type MyConfig struct {
ConfigName string
SqlConn string
RedisAddPort string
RedisAuth string
RedisDB string
LogOutput string
LogFilename string
LogLevel string
}
//MConfig
var MConfig *MyConfig
func RestMyConfig() *MyConfig {
MConfig = &MyConfig{
ConfigName: beego.AppConfig.String("config_name"),
SqlConn: beego.AppConfig.String("sqlconn"),
RedisAddPort: beego.AppConfig.String("redis_add_port"),
RedisAuth: beego.AppConfig.DefaultString("redis_auth", ""),
RedisDB: beego.AppConfig.DefaultString("redis_db", "0"),
LogOutput: beego.AppConfig.DefaultString("log_outpur", "console"),
LogFilename: beego.AppConfig.DefaultString("log_filename", "./log/ability.log"),
LogLevel: beego.AppConfig.DefaultString("log_Level", "debug"),
}
return MConfig
}
... ...
package log
import (
"encoding/json"
"github.com/astaxie/beego/logs"
)
type SetLoggerConfig interface {
MarshalString() string
Name() string
}
//LoggerConsole 日志输出到命令行
type LoggerConsole struct {
Level int `json:"level,omitempty"`
Color bool `json:"color,omitempty"`
}
//LoggerFile 日志输出到文件
type LoggerFile struct {
FileName string `json:"filename,omitempty"`
Maxlines int `json:"maxlines,omitempty"`
Maxsize int `json:"maxsize,omitempty"`
Daily bool `json:"daily,omitempty"`
MaxDays int `json:"maxdays,omitempty"`
Rotate bool `json:"rotate,omitempty"`
Level int `json:"level,omitempty"`
}
var (
_ SetLoggerConfig = &LoggerConsole{}
_ SetLoggerConfig = &LoggerFile{}
)
// log level
const (
LogLevelError int = logs.LevelError
LogLevelWarn int = logs.LevelWarning
LogLevelInfo int = logs.LevelInformational
LogLevelDebug int = logs.LevelDebug
)
func (config LoggerConsole) MarshalString() string {
bytedata, err := json.Marshal(config)
if err != nil {
return ""
}
return string(bytedata)
}
func (config LoggerConsole) Name() string {
return logs.AdapterConsole
}
func (config LoggerFile) MarshalString() string {
bytedata, err := json.Marshal(config)
if err != nil {
return ""
}
return string(bytedata)
}
func (config LoggerFile) Name() string {
return logs.AdapterFile
}
var logger *logs.BeeLogger
func ResetLog(config SetLoggerConfig, funcCall bool) {
logger = logs.GetBeeLogger()
logger.Async(1000)
out := config.Name()
logconf := config.MarshalString()
logger.EnableFuncCallDepth(funcCall)
logger.SetLogFuncCallDepth(3)
logger.SetLogger(out, logconf)
return
}
//LogLevel ...
func LogLevel(s string) (i int) {
switch s {
case "info":
i = LogLevelInfo
case "debug":
i = LogLevelDebug
case "warning":
i = LogLevelWarn
case "error":
i = LogLevelError
default:
i = LogLevelDebug
}
return
}
func Info(format string, v ...interface{}) {
logger.Info(format, v...)
}
func Debug(format string, v ...interface{}) {
logger.Debug(format, v...)
}
func Error(format string, v ...interface{}) {
logger.Error(format, v...)
}
func Warn(format string, v ...interface{}) {
logger.Warn(format, v...)
}
... ...
package redis
import (
"fmt"
"github.com/go-redis/redis"
)
//时间
const (
SECOND int64 = 1 //秒
MINUTE int64 = SECOND * 60 //分
HOUR int64 = MINUTE * 60 //小时
DAY int64 = HOUR * 24
WEEK int64 = DAY * 7
)
var RedisClient *redis.Client
func SetRedis(addr string, password string, db int) {
RedisClient = redis.NewClient(&redis.Options{
Addr: addr,
Password: password,
DB: db, //使用的库
})
_, err := RedisClient.Ping().Result()
if err != nil {
panic(fmt.Sprintf("connect redis err:%s", err))
}
}
func GetRedis() *redis.Client {
return RedisClient
}
... ...
package common
// type CommonErr struct {
// Err error
// Code string
// Message string
// }
// func (c *CommonErr) Error() string {
// return c.Message
// }
// func (c *CommonErr) Unwrap() error {
// return c.Err
// }
// func (c *CommonErr) CodeString() string {
// return c.Code
// }
... ...
#app的名称
appname = ability
#运行模式
runmode =${ProRunMode||local}
#是否自动渲染页面
autorender = false
#是否复制请求body
copyrequestbody = true
#开启应用内文档
EnableDocs = true
include "dev.conf"
include "prod.conf"
include "local.conf"
... ...
[dev]
config_name = "dev"
#----beego的默认配置 开始---
#端口号
httpport = 8081
#开启应用内监控
EnableAdmin = true
AdminPort = 8088
#---beego的默认配置 结束---
#---自定义配置 开始----
##数据库连接
sqlconn ="root:root@tcp(127.0.0.1:3306)/ability_display?charset=utf8"
##redis相关配置
redis_add_port = "127.0.0.1:6379"
redis_auth = ""
##log相关配置
##out_put:"console","file"
log_output = "file"
log_filename = "./log/ability.log"
# maxlines =
# maxsize =
# daily =
# maxdays =
# rotate =
log_level = "debug"
#---自定义配置 结束----
\ No newline at end of file
... ...
[local]
config_name = "local"
#----beego的默认配置 开始---
#端口号
httpport = 8081
#开启应用内监控
EnableAdmin = true
AdminPort = 8088
##---beego的默认配置 结束---
#---自定义配置 开始----
#数据库连接
sqlconn = "root:root@tcp(127.0.0.1:3306)/ability_display?charset=utf8"
#redis相关配置
redis_add_port = "127.0.0.1:6379"
redis_auth = ""
#log相关配置
#out_put:"console","file"
log_output = "file"
log_filename = "./log/ability.log"
# maxlines =
# maxsize =
# daily =
# maxdays =
# rotate =
log_level = "debug"
#---自定义配置 结束----
\ No newline at end of file
... ...
[prod]
config_name = "prod"
#----beego的默认配置 开始---
#端口号
httpport = 8080
##---beego的默认配置 结束---
#---自定义配置 开始----
#数据库连接
sqlconn = "root:root@tcp(127.0.0.1:3306)/ability_display?charset=utf8"
#redis相关配置
redis_add_port = "127.0.0.1:6379"
redis_auth = ""
#log相关配置
#out_put:"console","file"
log_output = "file"
log_filename = "./log/ability.log"
# maxlines =
# maxsize =
# daily =
# maxdays =
# rotate =
log_level = "debug"
#---自定义配置 结束----
\ No newline at end of file
... ...
package controllers
import (
"encoding/json"
"fmt"
"oppmg/common/log"
"oppmg/protocol"
"oppmg/services/serveauth"
"github.com/astaxie/beego/validation"
)
type AuthController struct {
BaseController
}
//URLMapping 实现ControllerInterface中的URLMapping
func (c *AuthController) URLMapping() {
c.Mapping("AccessToken", c.AccessToken)
}
func (c *AuthController) AccessToken() {
log.Debug("运行cotrollers")
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
var param protocol.RequestCheckSmsCode
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
log.Error("json 解析失败", err)
msg = protocol.BadRequestParam("00001")
return
}
valid := validation.Validation{}
ok, err := valid.Valid(&param)
if err != nil {
//TODO
log.Error("系统错误", err)
}
if !ok {
//TODO
log.Error("参数错误")
}
data, commErr := serveauth.GetAccessToken(param)
msg = protocol.NewReturnResponse(data, commErr)
return
}
//Demo 登录
func (c *AuthController) Demo() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
type Parameter struct {
}
var param Parameter
if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
fmt.Println("json 解析失败", err)
// msg.Code = "1"
return
}
/**/
return
}
... ...
package controllers
import (
"encoding/json"
"fmt"
"net/http"
"oppmg/common/log"
"oppmg/protocol"
"github.com/astaxie/beego"
)
//BaseHeader 请求的header数据
//减少在具体业务方法中使用 this.Ctx.Input.Header("xxxx")
type BaseHeader struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
//BaseController 基础
type BaseController struct {
beego.Controller
AppHead BaseHeader
}
//Options 实现beego.ControllerInterface 的接口
func (this *BaseController) Options() {
this.Ctx.Abort(http.StatusBadRequest, "")
}
//Prepare 实现beego.ControllerInterface 的接口
func (this *BaseController) Prepare() {
this.AppHead.AccessToken = this.Ctx.Input.Header("access_token")
this.AppHead.RefreshToken = this.Ctx.Input.Header("refresh_token")
//详细header待定 TODO
if this.Ctx.Input.RequestBody != nil {
log.Info(fmt.Sprintf("====>Recv data from client:\nHeadData: %s\n BodyData: %s", this.Ctx.Request.Header, string(this.Ctx.Input.RequestBody)))
} else {
log.Info(fmt.Sprintf("====>Recv data from client:\nHeadData: %s ", this.Ctx.Request.Header))
}
}
//Finish 实现beego.ControllerInterface 的接口
func (this *BaseController) Finish() {
strByte, _ := json.Marshal(this.Data["json"])
length := len(strByte)
if length > 5000 {
log.Info(fmt.Sprintf("<====Send to client: RspBodyData: %s......", string(strByte[:5000])))
} else {
log.Info(fmt.Sprintf("<====Send to client: RspBodyData: %s", string(strByte)))
}
}
func (this *BaseController) ResposeJson(msg *protocol.ResponseMessage) {
this.Data["json"] = msg
this.ServeJSON()
}
... ...
module oppmg
go 1.13
require (
github.com/astaxie/beego v1.10.0
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-redis/redis v6.15.6+incompatible
github.com/go-sql-driver/mysql v1.4.1
github.com/lib/pq v1.2.0 // indirect
github.com/onsi/ginkgo v1.10.3 // indirect
github.com/onsi/gomega v1.7.1 // indirect
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 // indirect
golang.org/x/crypto v0.0.0-20191119213627-4f8c1d86b1ba // indirect
google.golang.org/appengine v1.6.5 // indirect
gopkg.in/yaml.v2 v2.2.7 // indirect
)
... ...
github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
github.com/OwnLocal/goes v1.0.0/go.mod h1:8rIFjBGTue3lCU0wplczcUgt9Gxgrkkrw7etMIcn8TM=
github.com/astaxie/beego v1.10.0 h1:s0OZ1iUO0rl8+lwWZfPK/0GhQi1tFUcIClTevyz48Pg=
github.com/astaxie/beego v1.10.0/go.mod h1:0R4++1tUqERR0WYFWdfkcrsyoVBCG4DgpDGokT3yb+U=
github.com/astaxie/beego v1.12.0 h1:MRhVoeeye5N+Flul5PoVfD9CslfdoH+xqC/xvSQ5u2Y=
github.com/astaxie/beego v1.12.0/go.mod h1:fysx+LZNZKnvh4GED/xND7jWtjCR6HzydR2Hh2Im57o=
github.com/beego/goyaml2 v0.0.0-20130207012346-5545475820dd/go.mod h1:1b+Y/CofkYwXMUU0OhQqGvsY2Bvgr4j6jfT699wyZKQ=
github.com/beego/x2j v0.0.0-20131220205130-a0352aadc542/go.mod h1:kSeGC/p1AbBiEp5kat81+DSQrZenVBZXklMLaELspWU=
github.com/bradfitz/gomemcache v0.0.0-20180710155616-bc664df96737/go.mod h1:PmM6Mmwb0LSuEubjR8N7PtNe1KxZLtOUHtbeikc5h60=
github.com/casbin/casbin v1.7.0/go.mod h1:c67qKN6Oum3UF5Q1+BByfFxkwKvhwW57ITjqwtzR1KE=
github.com/cloudflare/golz4 v0.0.0-20150217214814-ef862a3cdc58/go.mod h1:EOBUe0h4xcZ5GoxqC5SDxFQ8gwyZPKQoEzownBlhI80=
github.com/couchbase/go-couchbase v0.0.0-20181122212707-3e9b6e1258bb/go.mod h1:TWI8EKQMs5u5jLKW/tsb9VwauIrMIxQG1r5fMsswK5U=
github.com/couchbase/gomemcached v0.0.0-20181122193126-5125a94a666c/go.mod h1:srVSlQLB8iXBVXHgnqemxUXqN6FCvClgCMPCsjBDR7c=
github.com/couchbase/goutils v0.0.0-20180530154633-e865a1461c8a/go.mod h1:BQwMFlJzDjFDG3DJUdU0KORxn88UlsOULuxLExMh3Hs=
github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGiisLwp9rITslkFNpZD5rz43tf41QFkTWY=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/edsrzf/mmap-go v0.0.0-20170320065105-0bce6a688712/go.mod h1:YO35OhQPt3KJa3ryjFM5Bs14WD66h8eGKpfaBNrHW5M=
github.com/elazarl/go-bindata-assetfs v1.0.0/go.mod h1:v+YaWX3bdea5J/mo8dSETolEo7R71Vk1u8bnjau5yw4=
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/go-redis/redis v6.14.2+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/go-redis/redis v6.15.6+incompatible h1:H9evprGPLI8+ci7fxQx6WNZHJSb7be8FqJQRhdQZ5Sg=
github.com/go-redis/redis v6.15.6+incompatible/go.mod h1:NAIEuMOZ/fxfXJIrKDQDz8wamY7mA7PouImQ2Jvg6kA=
github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA=
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1 h1:YF8+flBXS5eO826T4nzqPrxfhQThhXl0YzfuUPu4SBg=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
github.com/gomodule/redigo v2.0.0+incompatible/go.mod h1:B4C85qUVwatsJoIUNIfCRsp7qO0iAmpGFZ4EELWSbC4=
github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/lib/pq v1.2.0 h1:LXpIM/LZ5xGFhOpXAQUIMM1HdyqzVYM13zNdjCEEcA0=
github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
github.com/mattn/go-sqlite3 v2.0.0+incompatible h1:+afSeuaczjy4ZUN55wuDe1bCaAFBu0hg5Cf2Zw2ar0s=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.10.3 h1:OoxbjfXVZyod1fmWYhI7SEyaD8B00ynP3T+D5GiyHOY=
github.com/onsi/ginkgo v1.10.3/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/gomega v1.7.1 h1:K0jcRCwNQM3vFGh1ppMtDh/+7ApJrjldlX8fA0jDTLQ=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644 h1:X+yvsM2yrEktyI+b2qND5gpH8YhURn0k8OCaeRnkINo=
github.com/shiena/ansicolor v0.0.0-20151119151921-a422bbe96644/go.mod h1:nkxAfR/5quYxwPZhyDxgasBMnRtBZd0FCEpawpjMUFg=
github.com/siddontang/go v0.0.0-20180604090527-bdc77568d726/go.mod h1:3yhqj7WBBfRhbBlzyOC3gUxftwsU0u8gqevxwIHQpMw=
github.com/siddontang/ledisdb v0.0.0-20181029004158-becf5f38d373/go.mod h1:mF1DpOSOUiJRMR+FDqaqu3EBqrybQtrDDszLUZ6oxPg=
github.com/siddontang/rdb v0.0.0-20150307021120-fc89ed2e418d/go.mod h1:AMEsy7v5z92TR1JKMkLLoaOQk++LVnOKL3ScbJ8GNGA=
github.com/ssdb/gossdb v0.0.0-20180723034631-88f6b59b84ec/go.mod h1:QBvMkMya+gXctz3kmljlUCu/yB3GZ6oee+dUozsezQE=
github.com/syndtr/goleveldb v0.0.0-20181127023241-353a9fca669c/go.mod h1:Z4AUp2Km+PwemOoO/VB5AOx9XSsIItzFjoJlOSiYmn0=
github.com/wendal/errors v0.0.0-20130201093226-f66c77a7882b/go.mod h1:Q12BUT7DqIlHRmgv3RskH+UCM/4eqVMgI0EMmlSpAXc=
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85 h1:et7+NAX3lLIk5qUCTA9QelBjGE/NkhzYw/mhnr0s7nI=
golang.org/x/crypto v0.0.0-20181127143415-eb0de9b17e85/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191119213627-4f8c1d86b1ba h1:9bFeDpN3gTqNanMVqNcoR/pJQuP5uroC3t1D7eXozTE=
golang.org/x/crypto v0.0.0-20191119213627-4f8c1d86b1ba/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65 h1:+rhAzEzT3f4JtomfC371qB+0Ola2caSKcY69NUBZrRQ=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d h1:+R4KGOnez64A81RvjARKc4UT5/tI9ujCIVX+P5KiHuI=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
google.golang.org/appengine v1.6.5 h1:tycE03LOZYQNhDpS27tcQdAzLCVMaj7QT2SXxebnpCM=
google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo=
gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
... ...
2019/09/25 09:30:17.551 [D] [main.go:23] 应用启动
2019/09/25 09:30:17.602 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:41:04.196 [D] [proc.go:203] 应用启动
2019/09/25 09:41:04.245 [I] [asm_amd64.s:1357] http server Running on http://:8080
2019/09/25 09:41:51.479 [D] [main.go:23] 应用启动
2019/09/25 09:41:51.522 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:43:54.102 [D] [main.go:23] 应用启动
2019/09/25 09:43:54.148 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:44:26.483 [D] 应用启动
2019/09/25 09:44:26.527 [I] http server Running on http://:8080
2019/09/25 09:45:14.831 [D] 应用启动
2019/09/25 09:45:14.883 [I] http server Running on http://:8080
2019/09/25 09:46:11.373 [D] [main.go:23] 应用启动
2019/09/25 09:46:11.421 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:46:20.279 [D] 应用启动
2019/09/25 09:46:20.321 [I] http server Running on http://:8080
2019/09/25 09:46:36.286 [D] [main.go:23] 应用启动
2019/09/25 09:46:36.327 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:48:04.055 [D] [logger.go:70] log 配置:{"filename":"./log/ability.log"}
2019/09/25 09:48:04.058 [D] [main.go:23] 应用启动
2019/09/25 09:48:04.101 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:48:57.467 [D] [logger.go:68] log 配置:{"filename":"./log/ability.log"}
2019/09/25 09:48:57.472 [D] [main.go:23] 应用启动
2019/09/25 09:48:57.513 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:51:29.788 [D] [logger.go:68] log 配置:{"filename":"./log/ability.log"}
2019/09/25 09:51:29.790 [D] [main.go:24] 应用启动
2019/09/25 09:51:29.831 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:52:37.088 [D] [logger.go:72] log 配置:{"filename":"./log/ability.log"}
2019/09/25 09:52:37.091 [D] [main.go:24] 应用启动
2019/09/25 09:52:37.134 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:53:53.727 [D] [logger.go:74] log 配置:{"filename":"./log/ability.log"}
2019/09/25 09:53:53.730 [D] [main.go:24] 应用启动
2019/09/25 09:53:53.774 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:57:45.468 [D] [logger.go:75] log 配置:{"filename":"./log/ability.log"}
2019/09/25 09:57:45.471 [D] [main.go:24] 应用启动
2019/09/25 09:57:45.518 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:58:34.957 [D] [logger.go:75] log 配置:{"filename":"./log/ability.log"}
2019/09/25 09:58:34.961 [D] [main.go:24] 应用启动
2019/09/25 09:58:35.001 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:59:00.222 [D] [logger.go:75] log 配置:{"filename":"./log/ability.log"}
2019/09/25 09:59:00.224 [D] [main.go:24] 应用启动
2019/09/25 09:59:00.267 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:59:21.718 [D] [logger.go:75] log 配置:{"filename":"./log/ability.log"}
2019/09/25 09:59:21.720 [D] [main.go:24] 应用启动
2019/09/25 09:59:21.763 [I] [app.go:215] http server Running on http://:8080
2019/09/25 09:59:51.099 [D] [logger.go:76] log 配置:{"filename":"./log/ability.log"}
2019/09/25 09:59:51.102 [D] [main.go:24] 应用启动
2019/09/25 09:59:51.144 [I] [app.go:215] http server Running on http://:8080
2019/09/25 10:00:08.480 [D] [logger.go:76] log 配置:{"filename":"./log/ability.log"}
2019/09/25 10:00:08.482 [D] [main.go:24] 应用启动
2019/09/25 10:00:08.529 [I] [app.go:215] http server Running on http://:8080
2019/09/25 10:00:24.442 [D] [logger.go:76] log 配置:{"filename":"./log/ability.log"}
2019/09/25 10:00:24.444 [D] [main.go:24] 应用启动
2019/09/25 10:00:24.487 [I] [app.go:215] http server Running on http://:8080
2019/09/25 10:00:43.449 [D] [logger.go:76] log 配置:{"filename":"./log/ability.log","level":7}
2019/09/25 10:00:43.451 [D] [main.go:24] 应用启动
2019/09/25 10:00:43.491 [I] [app.go:215] http server Running on http://:8080
2019/09/25 10:01:06.019 [D] [logger.go:76] log 配置:{"filename":"./log/ability.log","level":7}
2019/09/25 10:01:06.021 [D] [main.go:23] 应用启动
2019/09/25 10:01:06.063 [I] [app.go:215] http server Running on http://:8080
2019/09/25 10:01:11.803 [D] [logger.go:76] log 配置:{"filename":"./log/ability.log","level":7}
2019/09/25 10:01:11.805 [D] [main.go:23] 应用启动
2019/09/25 10:01:11.849 [I] [app.go:215] http server Running on http://:8080
2019/09/25 10:01:12.837 [D] [logger.go:76] log 配置:{"filename":"./log/ability.log","level":7}
2019/09/25 10:01:12.838 [D] [main.go:23] 应用启动
2019/09/25 10:01:12.880 [I] [app.go:215] http server Running on http://:8080
2019/09/25 10:01:46.181 [D] [logger.go:76] log 配置:{"filename":"./log/ability.log","level":7}
2019/09/25 10:01:46.184 [D] [main.go:23] 应用启动
2019/09/25 10:01:46.231 [I] [app.go:215] http server Running on http://:8080
... ...
package main
import (
"oppmg/common"
_ "oppmg/routers"
"oppmg/common/config"
"oppmg/common/log"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
func main() {
common.ResetCommonConfig()
log.Debug("加载配置%s", config.MConfig.ConfigName)
orm.RegisterDataBase("default", "mysql", config.MConfig.SqlConn)
if beego.BConfig.RunMode == "dev" {
beego.BConfig.WebConfig.DirectoryIndex = true
beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
}
log.Debug("应用启动")
beego.Run()
}
... ...
package middleware
... ...
package middleware
import (
"oppmg/common/log"
"github.com/astaxie/beego/context"
)
//AuthToken ...
var AuthToken = func(ctx *context.Context) {
log.Debug("执行中间件AuthToken")
ctx.Output.Body([]byte("{}"))
return
}
//AppSwitch 使用外部变量停止处理新的请求
var AppSwitch = func(ctx *context.Context) {
return
}
... ...
不能预览此文件类型
package protocol
import (
"encoding/json"
)
//CustomErrParse 解析自定义错误结构体
type CustomErrParse interface {
ParseToMessage() *ResponseMessage
}
//ErrorMap 统一消息错误编码
type ErrorMap map[string]string
//Search 搜索错误描述
func (m ErrorMap) Search(code string) ErrorCode {
if v, ok := m[code]; ok {
return ErrorCode{
Errno: code,
Errmsg: v,
}
}
return ErrorCode{}
}
//ErrorCode 统一错误结构
type ErrorCode struct {
Errno string `json:"code"`
Errmsg string `json:"msg"`
}
//ResponseMessage 统一返回消息结构体
type ResponseMessage struct {
ErrorCode
Data interface{} `json:"data"`
}
func NewMesage(code string) *ResponseMessage {
return &ResponseMessage{
ErrorCode: SearchErr(code),
Data: nil,
}
}
//ErrWithMessage 自定义错误结构
type ErrWithMessage struct {
Err error `json:"-"`
ErrorCode
}
var (
_ CustomErrParse = new(ErrWithMessage)
_ error = new(ErrWithMessage)
)
//NewErrWithMessage 构建错误返回
//code:用于匹配统一消息错误编码 eRR:填充嵌套错误
func NewErrWithMessage(code string, eRR ...error) *ErrWithMessage {
r := &ErrWithMessage{
ErrorCode: SearchErr(code),
}
if len(eRR) > 0 {
r.Err = eRR[0]
}
return r
}
//Error 实现接口error 中的方法
//将ErrorCode转为json数据,建议用于日志记录
func (e ErrWithMessage) Error() string {
bt, _ := json.Marshal(e.ErrorCode)
return string(bt)
}
//Unwrap 接口实现
func (e ErrWithMessage) Unwrap() error {
return e.Err
}
//ParseToMessage 实现CustomErrParse的接口
func (e ErrWithMessage) ParseToMessage() *ResponseMessage {
return &ResponseMessage{
ErrorCode: e.ErrorCode,
Data: nil,
}
}
func SearchErr(code string) ErrorCode {
return errmessge.Search(code)
}
func NewReturnResponse(data interface{}, eRR error) *ResponseMessage {
var msg *ResponseMessage
if eRR == nil {
msg = NewMesage("0")
msg.Data = data
return msg
}
// fmt.Println("日志:" + eRR.Error())
if x, ok := eRR.(CustomErrParse); ok {
return x.ParseToMessage()
}
return NewMesage("1")
}
func BadRequestParam(code string) *ResponseMessage {
return NewMesage(code)
}
... ...
package protocol
import (
"encoding/json"
"testing"
)
func Test_Err(t *testing.T) {
errmsg := NewMesage(0)
bt1, _ := json.Marshal(errmsg)
t.Log(string(bt1))
normalmsg := NewErrWithMessage(0)
bt2, _ := json.Marshal(normalmsg)
t.Log(string(bt2))
}
... ...
package protocol
var errmessge ErrorMap = map[string]string{
"1": "系统异常",
"101": "clientId或clientSecret无效",
"113": "签名验证失败",
}
... ...
package protocol
//验证原手机号
//POST:/user/checkSmsCode
type RequestCheckSmsCode struct {
Captcha string `json:"captcha"`
}
//获取用户数据
//POST:/user/userInfo
type RequestUserInfo struct {
}
type DataUserInfo struct {
User UserInfo `json:"user"`
}
type UserInfo struct {
Uid int64 `json:"uid"` //用户id
Uname string `json:"uname"` //用户名称
Phone string `json:"phone"` //手机号码
Image UserImages `json:"image"` //用户头像
Did int64 `json:"did"` //部门id
Department string `json:"department"` //部门名称
Position string `json:"position"` //职位名称
Level int `json:"level"` //职位级别
EmployeeAttr EmployeeAttr `json:"employeeAttr"` //员工属性
ImToken string `json:"imToken"` //网易云信IM Token
}
const (
userLevelEmployee int = 0 //员工
userLevelBoss int = 1 //老板
)
type UserImages struct {
Path string `json:"path"` //图片路径
W int `json:"w"` //图片宽
H int `json:"h"` //图片高
}
type EmployeeAttr struct {
Id int64 `json:"id"`
Name string `json:"name"`
}
//修改手机号
//POST:/user/changePhone
type RequestChangePhone struct {
Phone string `json:"phone"`
Captcha string `json:"captcha"`
}
//重置密码
//POST:/user/resetPassword
type RequestResetPasssword struct {
NewPwd string `json:"newPwd"`
ConfirmPwd string `json:"configmPwd"`
}
//修改密码
//POST:/user/changePassword
type RequestChangePasssword struct {
NewPwd string `json:"newPwd"`
ConfirmPwd string `json:"configmPwd"`
OldPwd string `json:"oldPwd"`
}
... ...
package routers
import (
"oppmg/controllers"
"oppmg/middleware"
"github.com/astaxie/beego"
)
func init() {
nsAuth := beego.NewNamespace("/auth",
beego.NSBefore(middleware.AuthToken),
beego.NSRouter("/accessToken", &controllers.AuthController{}, "post:AccessToken"),
)
beego.AddNamespace(nsAuth)
}
... ...
package serveauth
import (
"oppmg/protocol"
)
func GetAccessToken(param protocol.RequestCheckSmsCode) (*protocol.DataUserInfo, error) {
data := &protocol.DataUserInfo{}
err := protocol.NewErrWithMessage("00000")
return data, err
}
... ...
package redisdata
const (
Key_App_Switch string = "app_switch"
Value_Switch_On string = "on"
Value_Switch_Off string = "off"
)
... ...
package redisdata
... ...
package encrypt
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"encoding/base64"
"encoding/hex"
"fmt"
"strconv"
"strings"
)
type KeySizeError int
func (k KeySizeError) Error() string {
return "fastEncryptDecode/fastEnDeCode: invalid key size " + strconv.Itoa(int(k)) + " | key size must be 16"
}
type ecbEncrypter ecb
type ecb struct {
b cipher.Block
blockSize int
}
func newECB(b cipher.Block) *ecb {
return &ecb{
b: b,
blockSize: b.BlockSize(),
}
}
// byte array to string
func ByteArr2Str(p []byte) string {
lp := len(p)
for i := 0; i < lp; i++ {
if p[i] == 0 {
return string(p[0:i])
}
}
return string(p)
}
func ByteArr2HexStr(bArr []byte) string {
buf := new(bytes.Buffer)
for _, b := range bArr {
s := strconv.FormatInt(int64(b&0xff), 16)
if len(s) == 1 {
buf.WriteString("0")
}
buf.WriteString(s)
}
return buf.String()
}
func Uint16ToBytes(n uint16) []byte {
return []byte{
byte(n),
byte(n >> 8),
}
}
func Uint32ToBytes(n uint32) []byte {
return []byte{
byte(n),
byte(n >> 8),
byte(n >> 16),
byte(n >> 24),
}
}
func Uint64ToBytes(n uint64) []byte {
return []byte{
byte(n),
byte(n >> 8),
byte(n >> 16),
byte(n >> 24),
byte(n >> 32),
byte(n >> 40),
byte(n >> 48),
byte(n >> 56),
}
}
func ByteArr2HexStrArr(bArr []byte) []string {
length := len(bArr)
slice := make([]string, length)
buf := new(bytes.Buffer)
for i := 0; i < length; i++ {
buf.Reset()
buf.WriteString("0x")
s := strconv.FormatInt(int64(bArr[i]&0xff), 16)
if len(s) == 1 {
buf.WriteString("0")
}
buf.WriteString(s)
slice[i] = buf.String()
}
return slice
}
func HexStr2ByteArr(hexString string) ([]byte, error) {
length := len(hexString) / 2
slice := make([]byte, length)
rs := []rune(hexString)
for i := 0; i < length; i++ {
s := string(rs[i*2 : i*2+2])
value, err := strconv.ParseInt(s, 16, 10)
if err != nil {
return nil, err
}
slice[i] = byte(value & 0xFF)
}
return slice, nil
}
func Utf82Unicode(code string) string {
cover := strconv.QuoteToASCII(code)
res := cover[1 : len(cover)-1]
return res
}
func Unicode2Utf8(code string) string {
unicodeTemp := strings.Split(code, "\\u")
var context string
for _, v := range unicodeTemp {
if len(v) < 1 {
continue
}
temp, err := strconv.ParseInt(v, 16, 32)
if err != nil {
panic(err)
}
context += fmt.Sprintf("%c", temp)
}
return context
}
//string to md5
func String2MD5(code string) string {
h := md5.New()
h.Write([]byte(code))
rs := hex.EncodeToString(h.Sum(nil))
return rs
}
func MD5Verify(code string, md5Str string) bool {
return 0 == strings.Compare(String2MD5(code), md5Str)
}
//MD5 hash
func MD5hash(code []byte) string {
h := md5.New()
h.Write(code)
rs := hex.EncodeToString(h.Sum(nil))
return rs
}
func checkKeySize(key []byte) error {
len := len(key)
if len != 16 {
return KeySizeError(len)
}
return nil
}
// AES encrypt pkcs7padding CBC, key for choose algorithm
func AES_CBC_PKCS7_Encrypt(plantText, key string) (string, error) {
res, err := AES_CBC_PKCS7_EncryptByte([]byte(plantText), []byte(key))
return ByteArr2Str(res), err
}
// AES encrypt pkcs7padding CBC, key for choose algorithm
func AES_CBC_PKCS7_EncryptByte(plantText, key []byte) ([]byte, error) {
err := checkKeySize(key)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
plantText = pKCS7Padding(plantText, block.BlockSize())
blockModel := cipher.NewCBCEncrypter(block, key)
cipherText := make([]byte, len(plantText))
blockModel.CryptBlocks(cipherText, plantText)
return cipherText, nil
}
func AES_CBC_PKCS7_Decrypt(cipherText, key string) (string, error) {
result, err := AES_CBC_PKCS7_DecryptByte([]byte(cipherText), []byte(key))
str := ByteArr2Str(result)
return str, err
}
func AES_CBC_PKCS7_DecryptByte(cipherText, key []byte) ([]byte, error) {
err := checkKeySize(key)
if err != nil {
return nil, err
}
keyBytes := []byte(key)
block, err := aes.NewCipher(keyBytes)
if err != nil {
return nil, err
}
blockModel := cipher.NewCBCDecrypter(block, keyBytes)
plantText := make([]byte, len(cipherText))
blockModel.CryptBlocks(plantText, cipherText)
plantText = pKCS7UnPadding(plantText, block.BlockSize())
return plantText, nil
}
//AES Decrypt pkcs7padding CBC, key for choose algorithm
func pKCS7UnPadding(plantText []byte, blockSize int) []byte {
length := len(plantText)
unPadding := int(plantText[length-1])
return plantText[:(length - unPadding)]
}
func pKCS7Padding(cipherText []byte, blockSize int) []byte {
padding := blockSize - len(cipherText)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padText...)
}
func AES_ECB_PKCS5_Encrypt(cipherText, key string) (string, error) {
result, err := AES_ECB_PKCS5_EncryptByte([]byte(cipherText), []byte(key))
str := ByteArr2Str(result)
return str, err
}
func AES_ECB_PKCS5_EncryptByte(cipherText, key []byte) ([]byte, error) {
err := checkKeySize(key)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
ecb := newECBEncrypter(block)
content := cipherText
content = PKCS5Padding(content, block.BlockSize())
crypted := make([]byte, len(content))
ecb.CryptBlocks(crypted, content)
// 普通base64编码加密 区别于urlsafe base64
return crypted, nil
}
func AES_ECB_PKCS5_Decrypt(cipherText, key string) (string, error) {
result, err := AES_ECB_PKCS5_DecryptByte([]byte(cipherText), []byte(key))
str := ByteArr2Str(result)
return str, err
}
func AES_ECB_PKCS5_DecryptByte(cipherText, key []byte) ([]byte, error) {
err := checkKeySize(key)
if err != nil {
return nil, err
}
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
blockMode := newECBDecrypter(block)
origData := make([]byte, len(cipherText))
blockMode.CryptBlocks(origData, cipherText)
origData = PKCS5UnPadding(origData)
return origData, nil
}
func Base64UrlSafeEncode(source []byte) string {
// Base64 Url Safe is the same as Base64 but does not contain '/' and '+' (replaced by '_' and '-') and trailing '=' are removed.
bytearr := base64.StdEncoding.EncodeToString(source)
safeurl := strings.Replace(string(bytearr), "/", "_", -1)
safeurl = strings.Replace(safeurl, "+", "-", -1)
safeurl = strings.Replace(safeurl, "=", "", -1)
return safeurl
}
func PKCS5Padding(cipherText []byte, blockSize int) []byte {
padding := blockSize - len(cipherText)%blockSize
padText := bytes.Repeat([]byte{byte(padding)}, padding)
return append(cipherText, padText...)
}
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
// 去掉最后一个字节 unpadding 次
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
// NewECBEncrypter returns a BlockMode which encrypts in electronic code book
// mode, using the given Block.
func newECBEncrypter(b cipher.Block) cipher.BlockMode {
return (*ecbEncrypter)(newECB(b))
}
func (x *ecbEncrypter) BlockSize() int {
return x.blockSize
}
func (x *ecbEncrypter) CryptBlocks(dst, src []byte) {
if len(src)%x.blockSize != 0 {
panic("crypto/cipher: input not full blocks")
}
if len(dst) < len(src) {
panic("crypto/cipher: output smaller than input")
}
for len(src) > 0 {
x.b.Encrypt(dst, src[:x.blockSize])
src = src[x.blockSize:]
dst = dst[x.blockSize:]
}
}
type ecbDecrypter ecb
// NewECBDecrypter returns a BlockMode which decrypts in electronic code book
// mode, using the given Block.
func newECBDecrypter(b cipher.Block) cipher.BlockMode {
return (*ecbDecrypter)(newECB(b))
}
func (x *ecbDecrypter) BlockSize() int {
return x.blockSize
}
func (x *ecbDecrypter) CryptBlocks(dst, src []byte) {
if len(src)%x.blockSize != 0 {
panic("crypto/cipher: input not full blocks")
}
if len(dst) < len(src) {
panic("crypto/cipher: output smaller than input")
}
for len(src) > 0 {
x.b.Decrypt(dst, src[:x.blockSize])
src = src[x.blockSize:]
dst = dst[x.blockSize:]
}
}
... ...
package utils
import (
"time"
jwt "github.com/dgrijalva/jwt-go"
)
var (
key = []byte("sx87sda0w7x7sd")
)
//MyToken ...
type MyToken struct {
jwt.StandardClaims
ID int `json:"id"`
}
//CreateJWTToken ...
func CreateJWTToken(id int) (string, error) {
nowTime := time.Now().Unix()
claims := MyToken{
StandardClaims: jwt.StandardClaims{
NotBefore: nowTime,
IssuedAt: nowTime,
ExpiresAt: 60 * 60 * 2, //过期时间
Issuer: "test_a",
},
ID: id,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString(key)
}
//ValidJWTToken ...
func ValidJWTToken(tokenString string) (*MyToken, error) {
token, err := jwt.ParseWithClaims(
tokenString,
&MyToken{},
func(token *jwt.Token) (interface{}, error) {
return key, nil
})
if err != nil {
return nil, err
}
if claims, ok := token.Claims.(*MyToken); ok && token.Valid {
// 验证成功,返回信息
return claims, nil
}
// 验证失败
return nil, err
}
... ...
package utils
import "time"
var localtime = time.FixedZone("UTC", 8*3600)
//LocalTimeZone 设定时区东八区
func LocalTimeZone() *time.Location {
return localtime
}
//LocalTime ....
func LocalTime() time.Time {
return new(time.Time).In(localtime)
}
... ...