作者 唐旭辉

新建

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