作者 yangfu

rename module name to ability

不能预览此文件类型
package controllers
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"strings"
"crypto/sha256"
"encoding/hex"
"gitlab.fjmaimaimai.com/mmm-go/ability/protocol"
s_auth "gitlab.fjmaimaimai.com/mmm-go/ability/services/auth"
"ability/protocol"
s_auth "ability/services/auth"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
"github.com/astaxie/beego"
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/validation"
"github.com/prometheus/client_golang/prometheus"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
)
var(
var (
//prometheus 监控endpoint
HTTPReqTotal *prometheus.CounterVec
auth s_auth.IAuthService = &s_auth.AuthService{}
auth s_auth.IAuthService = &s_auth.AuthService{}
)
type BaseController struct {
mybeego.BaseController
}
func init(){
func init() {
// HistogramVec 是一组Histogram
HTTPReqTotal= prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "request_count_vec",//http_requests_total
HTTPReqTotal = prometheus.NewCounterVec(prometheus.CounterOpts{
Name: "request_count_vec", //http_requests_total
Help: "total number of http requests made.",
}, []string{"method", "path"})
// 这里的"method"、"path"、"status" 都是label , "status"
... ... @@ -43,18 +43,20 @@ func init(){
// log.Error(err)
//}
}
var DefaultController *BaseController = &BaseController{}
//Valid valid struct
func (this *BaseController)Valid(obj interface{})(result bool ,msg *mybeego.Message){
func (this *BaseController) Valid(obj interface{}) (result bool, msg *mybeego.Message) {
/*校验*/
var err error
valid :=validation.Validation{}
result,err= valid.Valid(obj)
if err!=nil{
valid := validation.Validation{}
result, err = valid.Valid(obj)
if err != nil {
msg = mybeego.NewMessage(1)
return
}
if !result{
if !result {
for _, err := range valid.Errors {
log.Error(err.Key, err.Message)
}
... ... @@ -63,16 +65,17 @@ func (this *BaseController)Valid(obj interface{})(result bool ,msg *mybeego.Mess
}
return
}
//GenMessage genarate a response message
func (this *BaseController)GenMessage(rsp interface{},err error)*mybeego.Message{
func (this *BaseController) GenMessage(rsp interface{}, err error) *mybeego.Message {
var msg *mybeego.Message
if err==nil{
if err == nil {
msg = mybeego.NewMessage(0)
msg.Data = rsp
return msg
}
//log.Error(err)
if e,ok :=err.(common.Error);ok{
if e, ok := err.(common.Error); ok {
msg = mybeego.NewMessage(e.Code)
msg.Data = rsp
return msg
... ... @@ -80,21 +83,22 @@ func (this *BaseController)GenMessage(rsp interface{},err error)*mybeego.Message
msg = mybeego.NewMessage(1)
return msg
}
//获取请求头信息
func GetRequestHeader(ctx *context.Context)*protocol.RequestHeader{
h :=&protocol.RequestHeader{}
func GetRequestHeader(ctx *context.Context) *protocol.RequestHeader {
h := &protocol.RequestHeader{}
h.AccessToken = ctx.Input.Header("x-mmm-accesstoken")
h.AppProject = ctx.Input.Header("x-mmm-appproject")
h.DeviceType = ctx.Input.Header("x-mmm-devicetype")
h.Sign = ctx.Input.Header("x-mmm-sign")
h.Uuid = ctx.Input.Header("x-mmm-uuid")
h.TimeStamp = ctx.Input.Header("x-mmm-timestamp")
h.Uid,_=strconv.ParseInt(ctx.Input.Header("uid"),10,64)//需要uid写入到header里面
h.Uid, _ = strconv.ParseInt(ctx.Input.Header("uid"), 10, 64) //需要uid写入到header里面
return h
}
//过滤器
func FilterComm(ctx *context.Context){
func FilterComm(ctx *context.Context) {
//if strings.HasSuffix(ctx.Request.RequestURI,"login"){
// return
//}
... ... @@ -102,26 +106,26 @@ func FilterComm(ctx *context.Context){
//统计
MetricCounter(ctx)
if beego.BConfig.RunMode!="prod"{
if beego.BConfig.RunMode != "prod" {
return
}
//1.检查签名
if !CheckSign(ctx){
if !CheckSign(ctx) {
return
}
//2.检查token是否有效
if !CheckToken(ctx){
if !CheckToken(ctx) {
return
}
//3.查重uuid
if !CheckUuid(ctx){
if !CheckUuid(ctx) {
return
}
return
}
func MetricCounter(ctx *context.Context){
func MetricCounter(ctx *context.Context) {
// 请求数加1
HTTPReqTotal.With(prometheus.Labels{
"method": ctx.Request.Method,
... ... @@ -129,70 +133,73 @@ func MetricCounter(ctx *context.Context){
//"status": strconv.Itoa(c.Writer.Status()),
}).Inc()
}
//检查签名
func CheckSign(ctx *context.Context)(result bool){
var(
h *protocol.RequestHeader
sign string
func CheckSign(ctx *context.Context) (result bool) {
var (
h *protocol.RequestHeader
sign string
signHex string
)
result = true
h =GetRequestHeader(ctx)
h = GetRequestHeader(ctx)
//1.检查签名
sign =fmt.Sprintf("v!(MmM%v%v%vMmM)i^",h.TimeStamp,h.Uuid,h.AccessToken)
sha256:=sha256.New()
sign = fmt.Sprintf("v!(MmM%v%v%vMmM)i^", h.TimeStamp, h.Uuid, h.AccessToken)
sha256 := sha256.New()
sha256.Write([]byte(sign))
signHex = hex.EncodeToString(sha256.Sum(nil))
if strings.Compare(signHex,h.Sign)!=0{
msg :=mybeego.NewMessage(113)
log.Error(fmt.Sprintf("%v req:%v resp:%v %v",ctx.Request.RequestURI,common.AssertJson(h),common.AssertJson(msg),signHex))
if strings.Compare(signHex, h.Sign) != 0 {
msg := mybeego.NewMessage(113)
log.Error(fmt.Sprintf("%v req:%v resp:%v %v", ctx.Request.RequestURI, common.AssertJson(h), common.AssertJson(msg), signHex))
ctx.Output.JSON(msg, false, false)
result =false
result = false
return
}
return
}
//检查access_token
func CheckToken(ctx *context.Context)(result bool){
func CheckToken(ctx *context.Context) (result bool) {
var (
msg *mybeego.Message
)
result = true
defer func(){
if msg!=nil{
result =false
ctx.Output.JSON(msg,false,false)
defer func() {
if msg != nil {
result = false
ctx.Output.JSON(msg, false, false)
}
}()
token := ctx.Input.Header("x-mmm-accesstoken")
if rsp,err:=auth.CheckToken(&protocol.CheckTokenRequest{Token:token});(err!=nil || rsp.UserInfo==nil){
msg = DefaultController.GenMessage(rsp,err)
log.Error(fmt.Sprintf("%v req:%v resp:%v",ctx.Request.RequestURI,token,common.AssertJson(msg)))
if rsp, err := auth.CheckToken(&protocol.CheckTokenRequest{Token: token}); err != nil || rsp.UserInfo == nil {
msg = DefaultController.GenMessage(rsp, err)
log.Error(fmt.Sprintf("%v req:%v resp:%v", ctx.Request.RequestURI, token, common.AssertJson(msg)))
return
}else{
if rsp.UserInfo!=nil{
} else {
if rsp.UserInfo != nil {
//设置附加数据
ctx.Request.Header.Add("uid",fmt.Sprintf("%v",rsp.UserInfo.Uuid))
ctx.Request.Header.Add("uid", fmt.Sprintf("%v", rsp.UserInfo.Uuid))
}
}
return
}
//检查Uuid
func CheckUuid(ctx *context.Context)(result bool){
func CheckUuid(ctx *context.Context) (result bool) {
var (
msg *mybeego.Message
)
result = true
defer func(){
if msg!=nil{
result =false
ctx.Output.JSON(msg,false,false)
defer func() {
if msg != nil {
result = false
ctx.Output.JSON(msg, false, false)
}
}()
uuid := ctx.Input.Header("x-mmm-uuid")
msg = DefaultController.GenMessage(auth.CheckUuid(&protocol.CheckUuidRequest{Uuid:uuid}))
if msg!=nil{
log.Error(fmt.Sprintf("%v req:%v resp:%v",ctx.Request.RequestURI,uuid,common.AssertJson(msg)))
uuid := ctx.Input.Header("x-mmm-uuid")
msg = DefaultController.GenMessage(auth.CheckUuid(&protocol.CheckUuidRequest{Uuid: uuid}))
if msg != nil {
log.Error(fmt.Sprintf("%v req:%v resp:%v", ctx.Request.RequestURI, uuid, common.AssertJson(msg)))
}
return
}
\ No newline at end of file
}
... ...
... ... @@ -3,15 +3,15 @@ package v1
import (
"encoding/json"
"gitlab.fjmaimaimai.com/mmm-go/ability/controllers"
"gitlab.fjmaimaimai.com/mmm-go/ability/protocol"
s_auth "gitlab.fjmaimaimai.com/mmm-go/ability/services/auth"
"ability/controllers"
"ability/protocol"
s_auth "ability/services/auth"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
)
var(
var (
auth s_auth.IAuthService = &s_auth.AuthService{}
)
... ... @@ -19,19 +19,20 @@ type AuthController struct {
controllers.BaseController
}
//Login
func(this *AuthController)Login(){
// Login
// @router /login [post]
func (this *AuthController) Login() {
var msg *mybeego.Message
defer func(){
defer func() {
this.Resp(msg)
}()
var request *protocol.LoginRequest
if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = mybeego.NewMessage(1)
return
}
if b,m :=this.Valid(request);!b{
if b, m := this.Valid(request); !b {
msg = m
return
}
... ... @@ -39,18 +40,19 @@ func(this *AuthController)Login(){
}
//SmsCode
func(this *AuthController)SmsCode(){
// @router /smsCode [post]
func (this *AuthController) SmsCode() {
var msg *mybeego.Message
defer func(){
defer func() {
this.Resp(msg)
}()
var request *protocol.SmsCodeRequest
if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = mybeego.NewMessage(1)
return
}
if b,m :=this.Valid(request);!b{
if b, m := this.Valid(request); !b {
msg = m
return
}
... ... @@ -58,18 +60,19 @@ func(this *AuthController)SmsCode(){
}
//UpdateDevice
func(this *AuthController)UpdateDevice(){
// @router /updateDevice [post]
func (this *AuthController) UpdateDevice() {
var msg *mybeego.Message
defer func(){
defer func() {
this.Resp(msg)
}()
var request *protocol.UpdateDeviceRequest
if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = mybeego.NewMessage(1)
return
}
if b,m :=this.Valid(request);!b{
if b, m := this.Valid(request); !b {
msg = m
return
}
... ... @@ -77,18 +80,19 @@ func(this *AuthController)UpdateDevice(){
}
//AccessToken
func(this *AuthController)AccessToken(){
// @router /accessToken [post]
func (this *AuthController) AccessToken() {
var msg *mybeego.Message
defer func(){
defer func() {
this.Resp(msg)
}()
var request *protocol.AccessTokenRequest
if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = mybeego.NewMessage(1)
return
}
if b,m :=this.Valid(request);!b{
if b, m := this.Valid(request); !b {
msg = m
return
}
... ... @@ -96,18 +100,19 @@ func(this *AuthController)AccessToken(){
}
//RefreshToken
func(this *AuthController)RefreshToken(){
// @router /refreshToken [post]
func (this *AuthController) RefreshToken() {
var msg *mybeego.Message
defer func(){
defer func() {
this.Resp(msg)
}()
var request *protocol.RefreshTokenRequest
if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = mybeego.NewMessage(1)
return
}
if b,m :=this.Valid(request);!b{
if b, m := this.Valid(request); !b {
msg = m
return
}
... ...
package v1
import (
"gitlab.fjmaimaimai.com/mmm-go/ability/controllers"
"gitlab.fjmaimaimai.com/mmm-go/ability/protocol"
"gitlab.fjmaimaimai.com/mmm-go/ability/services/upload"
"ability/controllers"
"ability/protocol"
"ability/services/upload"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
... ... @@ -13,16 +13,17 @@ type UploadController struct {
controllers.BaseController
}
//Image
func(this *UploadController)Image(){
var(
// Image
// @router /image [post]
func (this *UploadController) Image() {
var (
msg *mybeego.Message
err error
)
defer func(){
defer func() {
this.Resp(msg)
}()
var request = &protocol.FileRequest{}
var request = &protocol.FileRequest{}
//if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
// log.Error(err)
// msg = mybeego.NewMessage(1)
... ... @@ -32,23 +33,24 @@ func(this *UploadController)Image(){
// msg = m
// return
//}
if request.Files,err =this.GetFiles("file");err!=nil{
if request.Files, err = this.GetFiles("file"); err != nil {
log.Error(err)
return
}
msg = this.GenMessage(upload.Image(request))
}
//Voice
func(this *UploadController)Voice(){
// Image
// @router /voice [post]
func (this *UploadController) Voice() {
var (
msg *mybeego.Message
err error
)
defer func(){
defer func() {
this.Resp(msg)
}()
var request = &protocol.FileRequest{}
var request = &protocol.FileRequest{}
//if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
// log.Error(err)
// msg = mybeego.NewMessage(1)
... ... @@ -58,9 +60,9 @@ func(this *UploadController)Voice(){
// msg = m
// return
//}
if request.Files,err =this.GetFiles("file");err!=nil{
if request.Files, err = this.GetFiles("file"); err != nil {
log.Error(err)
return
}
msg = this.GenMessage(upload.Voice(request))
}
\ No newline at end of file
}
... ...
... ... @@ -3,34 +3,31 @@ package v1
import (
"encoding/json"
"gitlab.fjmaimaimai.com/mmm-go/ability/controllers"
"gitlab.fjmaimaimai.com/mmm-go/ability/protocol"
"gitlab.fjmaimaimai.com/mmm-go/ability/services/version"
"ability/controllers"
"ability/protocol"
"ability/services/version"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
)
type VersionController struct {
controllers.BaseController
}
//GetLatestVersionInfo
func(this *VersionController)GetLatestVersionInfo(){
func (this *VersionController) GetLatestVersionInfo() {
var msg *mybeego.Message
defer func(){
defer func() {
this.Resp(msg)
}()
var request *protocol.GetLatestVersionInfoRequest
if err:=json.Unmarshal(this.ByteBody,&request);err!=nil{
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = mybeego.NewMessage(1)
return
}
if b,m :=this.Valid(request);!b{
if b, m := this.Valid(request); !b {
msg = m
return
}
... ...
module gitlab.fjmaimaimai.com/mmm-go/ability
module ability
go 1.12
require (
github.com/astaxie/beego v1.10.0
github.com/go-sql-driver/mysql v1.4.1
github.com/prometheus/client_golang v1.1.0
github.com/smartystreets/goconvey v0.0.0-20190731233626-505e41936337
gitlab.fjmaimaimai.com/mmm-go/gocomm v0.0.1
google.golang.org/appengine v1.6.2 // indirect
... ...
package repository
import "gitlab.fjmaimaimai.com/mmm-go/ability/models"
import "ability/models"
type IUserRepository interface {
GetUsersByMobile(mobile string)(v *models.Users, err error)
GetUserInfoByMobile(mobile string)(v *models.UserInfo, err error)
GetUsersByMobile(mobile string) (v *models.Users, err error)
GetUserInfoByMobile(mobile string) (v *models.UserInfo, err error)
}
func assertImplement(){
func assertImplement() {
var _ IUserRepository = (*UserRepository)(nil)
}
type UserRepository struct {}
type UserRepository struct{}
func (r *UserRepository)GetUsersByMobile(mobile string)(v *models.Users, err error) {
func (r *UserRepository) GetUsersByMobile(mobile string) (v *models.Users, err error) {
return models.GetUsersByMobile(mobile)
}
func (r *UserRepository)GetUserInfoByMobile(mobile string)(v *models.UserInfo, err error) {
func (r *UserRepository) GetUserInfoByMobile(mobile string) (v *models.UserInfo, err error) {
return models.GetUserInfoByMobile(mobile)
}
\ No newline at end of file
}
... ...
package main
import (
"ability/controllers"
"ability/protocol"
_ "ability/routers"
"github.com/astaxie/beego"
_ "github.com/go-sql-driver/mysql"
"gitlab.fjmaimaimai.com/mmm-go/ability/controllers"
"gitlab.fjmaimaimai.com/mmm-go/ability/protocol"
_ "gitlab.fjmaimaimai.com/mmm-go/ability/routers"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/config"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/orm"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/redis"
)
func init(){
func init() {
log.InitLog(config.Logger{
Filename:"app.log",
Level:"7",
Filename: "app.log",
Level: "7",
})
err:= redis.InitWithDb(100,beego.AppConfig.String("redis_add_port"),beego.AppConfig.String("redis_auth"),"0")
if err!=nil{
err := redis.InitWithDb(100, beego.AppConfig.String("redis_add_port"), beego.AppConfig.String("redis_auth"), "0")
if err != nil {
log.Fatal(err)
panic(err)
}
orm.NewBeeormEngine(config.Mysql{
DataSource:beego.AppConfig.String("data_source"),
MaxIdle: 100,
MaxOpen:100,
DataSource: beego.AppConfig.String("data_source"),
MaxIdle: 100,
MaxOpen: 100,
})
}
func main() {
defer func(){
defer func() {
log.Info("app on stop!")
}()
beego.InsertFilter("/*",beego.BeforeRouter,controllers.FilterComm)
beego.InsertFilter("/*", beego.BeforeRouter, controllers.FilterComm)
protocol.InitMessageCode()
log.Info("app on start!")
log.Info("Beego Run Mode:",beego.BConfig.RunMode)
log.Info("Beego Run Mode:", beego.BConfig.RunMode)
beego.Run()
}
... ...
package protocol
import "gitlab.fjmaimaimai.com/mmm-go/ability/models"
import "ability/models"
const (
LoginTypePassPord ="signInPassword"
LoginTypeSmdcode ="signInCaptcha"
const (
LoginTypePassPord = "signInPassword"
LoginTypeSmdcode = "signInCaptcha"
)
var Nums =[]byte("0123456789")
var Nums = []byte("0123456789")
type RequestHeader struct {
TimeStamp string
Uuid string
Sign string
DeviceType string
AppProject string
TimeStamp string
Uuid string
Sign string
DeviceType string
AppProject string
AccessToken string
Uid int64
Uid int64
}
/*Login */
type LoginRequest struct {
Phone string `json:"phone" valid:"Required;Mobile"`
Code string `json:"code"`
Phone string `json:"phone" valid:"Required;Mobile"`
Code string `json:"code"`
GrantType string `json:"grantType" valid:"Required"`
PassWord string `json:"password"`
ClientId string `json:"clientId" valid:"Required"`
PassWord string `json:"password"`
ClientId string `json:"clientId" valid:"Required"`
}
type LoginResponse struct {
AuthCode string `json:"authCode"`
... ... @@ -33,9 +33,9 @@ type LoginResponse struct {
/*SmsCode*/
type SmsCodeRequest struct {
Phone string `json:"phone" valid:"Required;Mobile"`
Content string `json:"-"`
SendType string `json:"send_type"`//sms_login_code sms_change_mobile
Phone string `json:"phone" valid:"Required;Mobile"`
Content string `json:"-"`
SendType string `json:"send_type"` //sms_login_code sms_change_mobile
}
type SmsCodeResponse struct {
... ... @@ -44,7 +44,7 @@ type SmsCodeResponse struct {
/*UpdateDevice*/
type UpdateDeviceRequest struct {
ClientId string `json:"clientId" valid:"Required"`
ClientId string `json:"clientId" valid:"Required"`
DeviceToken string `json:"deviceToken"`
}
type UpdateDeviceResponse struct {
... ... @@ -52,35 +52,35 @@ type UpdateDeviceResponse struct {
/*AccessToken */
type AccessTokenRequest struct {
ClientId string `json:"clientId" valid:"Required"`
ClientId string `json:"clientId" valid:"Required"`
ClientSecret string `json:"clientSecret" valid:"Required"`
AuthCode string `json:"authCode" valid:"Required"`
AuthCode string `json:"authCode" valid:"Required"`
}
type AccessTokenResponse struct {
RefreshToken string `json:"refreshToken"`
AccessToken string `json:"accessToken"`
ExpiresIn int `json:"expiresIn"`
AccessToken string `json:"accessToken"`
ExpiresIn int `json:"expiresIn"`
}
/*RefreshToken */
type RefreshTokenRequest struct {
ClientId string `json:"clientId" valid:"Required"`
ClientId string `json:"clientId" valid:"Required"`
ClientSecret string `json:"clientSecret" valid:"Required"`
RefreshToken string `json:"refreshToken" valid:"Required"`
Uid int64 `json:"-"`
Uid int64 `json:"-"`
LoginType string `json:"-"`
}
type RefreshTokenResponse struct {
RefreshToken string `json:"refreshToken"`
AccessToken string `json:"accessToken"`
ExpiresIn int `json:"expiresIn"`
AccessToken string `json:"accessToken"`
ExpiresIn int `json:"expiresIn"`
}
type Access struct {
Uid int64
Type string
AccessToken string
Uid int64
Type string
AccessToken string
RefreshToken string
}
... ... @@ -89,15 +89,13 @@ type CheckTokenRequest struct {
Token string
}
type CheckTokenResponse struct {
IsValid bool //true:过期 false:没有过期
IsValid bool //true:过期 false:没有过期
UserInfo *models.UserInfo
}
/*CheckUuid */
type CheckUuidRequest struct {
Uuid string
}
type CheckUuidResponse struct {
}
... ...
package routers
import (
"ability/controllers/v1"
"github.com/astaxie/beego"
"github.com/prometheus/client_golang/prometheus/promhttp"
"gitlab.fjmaimaimai.com/mmm-go/ability/controllers/v1"
)
var nsV1 *beego.Namespace
func init() {
nsV1=beego.NewNamespace("/v1")
/*user controller*/
{
user :=&v1.UserController{}
nsV1.Router("/user/login",user,"post:Login")
}
/*auth controller*/
{
auth :=&v1.AuthController{}
nsV1.Router("/auth/login",auth,"post:Login")
nsV1.Router("/auth/accessToken",auth,"post:AccessToken")
nsV1.Router("/auth/refreshToken",auth,"post:RefreshToken")
nsV1.Router("/auth/smsCode",auth,"post:SmsCode")
}
/*image controller*/
{
upload :=&v1.UploadController{}
nsV1.Router("/upload/image",upload,"post:Image")
nsV1.Router("/upload/voice",upload,"post:Voice")
}
{
version :=&v1.VersionController{}
nsV1.Router("/version/getLatestVersionInfo",version,"post:GetLatestVersionInfo")
}
beego.SetStaticPath("/file/ab",beego.AppConfig.String("source_path"))
beego.Handler("/metrics", promhttp.Handler())
nsV1 := beego.NewNamespace("v1",
beego.NSNamespace("auth", beego.NSInclude(&v1.AuthController{})),
beego.NSNamespace("upload", beego.NSInclude(&v1.UploadController{})),
beego.NSNamespace("version", beego.NSInclude(&v1.VersionController{})),
)
beego.AddNamespace(nsV1)
beego.SetStaticPath("/file/ab", beego.AppConfig.String("source_path"))
beego.Handler("/metrics", promhttp.Handler())
}
... ...
... ... @@ -8,281 +8,289 @@ import (
"strings"
"time"
"gitlab.fjmaimaimai.com/mmm-go/ability/internal/repository"
"gitlab.fjmaimaimai.com/mmm-go/ability/models"
"gitlab.fjmaimaimai.com/mmm-go/ability/protocol"
s_sms "gitlab.fjmaimaimai.com/mmm-go/ability/services/sms"
"ability/internal/repository"
"ability/models"
"ability/protocol"
s_sms "ability/services/sms"
"github.com/astaxie/beego"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/redis"
comm_time "gitlab.fjmaimaimai.com/mmm-go/gocomm/time"
"github.com/astaxie/beego"
)
type IAuthService interface {
Login(request *protocol.LoginRequest)(rsp *protocol.LoginResponse,err error)
AccessToken(request *protocol.AccessTokenRequest)(rsp *protocol.AccessTokenResponse,err error)
RefreshToken(request *protocol.RefreshTokenRequest)(rsp *protocol.RefreshTokenResponse,err error)
UpdateDevice(request *protocol.UpdateDeviceRequest)(rsp *protocol.UpdateDeviceResponse,err error)
CheckToken(request *protocol.CheckTokenRequest)(rsp *protocol.CheckTokenResponse,err error)
CheckUuid(request *protocol.CheckUuidRequest)(rsp *protocol.CheckUuidResponse,err error)
SmsCode(request *protocol.SmsCodeRequest)(rsp *protocol.SmsCodeResponse,err error)
Login(request *protocol.LoginRequest) (rsp *protocol.LoginResponse, err error)
AccessToken(request *protocol.AccessTokenRequest) (rsp *protocol.AccessTokenResponse, err error)
RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshTokenResponse, err error)
UpdateDevice(request *protocol.UpdateDeviceRequest) (rsp *protocol.UpdateDeviceResponse, err error)
CheckToken(request *protocol.CheckTokenRequest) (rsp *protocol.CheckTokenResponse, err error)
CheckUuid(request *protocol.CheckUuidRequest) (rsp *protocol.CheckUuidResponse, err error)
SmsCode(request *protocol.SmsCodeRequest) (rsp *protocol.SmsCodeResponse, err error)
}
type AuthService struct {}
type AuthService struct{}
func assertImplement(){
func assertImplement() {
var _ IAuthService = (*AuthService)(nil)
}
var(
var (
//服务
sms s_sms.ISmsService = &s_sms.YunPianSmsService{}
sms s_sms.ISmsService = &s_sms.YunPianSmsService{}
//仓储
UserRepository repository.IUserRepository =&repository.UserRepository{}
UserRepository repository.IUserRepository = &repository.UserRepository{}
)
//登录
func (s *AuthService)Login(request *protocol.LoginRequest)(rsp *protocol.LoginResponse,err error){
func (s *AuthService) Login(request *protocol.LoginRequest) (rsp *protocol.LoginResponse, err error) {
var (
user *models.Users
user *models.Users
userInfo *models.UserInfo
result bool
result bool
)
user,err =UserRepository.GetUsersByMobile(request.Phone)
if err!=nil{
user, err = UserRepository.GetUsersByMobile(request.Phone)
if err != nil {
log.Error(err)
err =common.NewError(2020,err)//账号不存在
err = common.NewError(2020, err) //账号不存在
return
}
switch request.GrantType {
case protocol.LoginTypePassPord:
if strings.Compare(user.Password,request.PassWord)==0{
if strings.Compare(user.Password, request.PassWord) == 0 {
goto Success
}else{
err =common.NewError(2021,err)//登录密码错误
} else {
err = common.NewError(2021, err) //登录密码错误
return
}
break
case protocol.LoginTypeSmdcode:
if result,err=CheckSmsCode(request.Phone,request.Code,protocol.SmsLoginCode);result && err==nil{
if result, err = CheckSmsCode(request.Phone, request.Code, protocol.SmsLoginCode); result && err == nil {
goto Success
}else{
} else {
return
}
default:
err =fmt.Errorf("grantType error")
err = fmt.Errorf("grantType error")
return
}
Success:
{
userInfo,err =UserRepository.GetUserInfoByMobile(request.Phone)
if err!=nil{
log.Error(err)
return
}
rsp =&protocol.LoginResponse{AuthCode:userInfo.Auth}
Success:
{
userInfo, err = UserRepository.GetUserInfoByMobile(request.Phone)
if err != nil {
log.Error(err)
return
}
rsp = &protocol.LoginResponse{AuthCode: userInfo.Auth}
return
}
return
}
//更新设备信息
func (s *AuthService)UpdateDevice(request *protocol.UpdateDeviceRequest)(rsp *protocol.UpdateDeviceResponse,err error){
return nil,nil
func (s *AuthService) UpdateDevice(request *protocol.UpdateDeviceRequest) (rsp *protocol.UpdateDeviceResponse, err error) {
return nil, nil
}
//获取accessToken
func (s *AuthService)AccessToken(request *protocol.AccessTokenRequest)(rsp *protocol.AccessTokenResponse,err error){
func (s *AuthService) AccessToken(request *protocol.AccessTokenRequest) (rsp *protocol.AccessTokenResponse, err error) {
var (
userInfo *models.UserInfo
)
userInfo,err = models.GetUserInfoByClientId(request.ClientId)
if err!=nil{
userInfo, err = models.GetUserInfoByClientId(request.ClientId)
if err != nil {
return
}
if strings.Compare(userInfo.Auth,request.AuthCode)!=0{
err = common.NewErrorWithMsg(2,"auth code error.")
if strings.Compare(userInfo.Auth, request.AuthCode) != 0 {
err = common.NewErrorWithMsg(2, "auth code error.")
return
}
//valid token
rsp = &protocol.AccessTokenResponse{
RefreshToken:userInfo.RefreshToken,
AccessToken:userInfo.AccessToken,
ExpiresIn:3600,
RefreshToken: userInfo.RefreshToken,
AccessToken: userInfo.AccessToken,
ExpiresIn: 3600,
}
return
}
//刷新token
func (s *AuthService)RefreshToken(request *protocol.RefreshTokenRequest)(rsp *protocol.RefreshTokenResponse,err error){
func (s *AuthService) RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshTokenResponse, err error) {
var (
userInfo *models.UserInfo
userInfo *models.UserInfo
newAccess *protocol.Access
)
userInfo,err = models.GetUserInfoByClientId(request.ClientId)
if err!=nil{
userInfo, err = models.GetUserInfoByClientId(request.ClientId)
if err != nil {
return
}
if strings.Compare(userInfo.RefreshToken,request.RefreshToken)!=0{
err = common.NewErrorWithMsg(2,"refresh token error.")
if strings.Compare(userInfo.RefreshToken, request.RefreshToken) != 0 {
err = common.NewErrorWithMsg(2, "refresh token error.")
return
}
request.Uid,request.LoginType = userInfo.Id,"mobile"
if newAccess,err =refreshToken(request);err!=nil{
request.Uid, request.LoginType = userInfo.Id, "mobile"
if newAccess, err = refreshToken(request); err != nil {
return
}
rsp = &protocol.RefreshTokenResponse{
AccessToken:newAccess.AccessToken,
RefreshToken:newAccess.RefreshToken,
ExpiresIn:3600,
AccessToken: newAccess.AccessToken,
RefreshToken: newAccess.RefreshToken,
ExpiresIn: 3600,
}
return
}
//刷新token loginType mobile im web
func refreshToken(request *protocol.RefreshTokenRequest)(rsp *protocol.Access,err error){
if request.Uid==0{
func refreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.Access, err error) {
if request.Uid == 0 {
return
}
return nil,nil
return nil, nil
}
//检查token有效性
func (s *AuthService)CheckToken(request *protocol.CheckTokenRequest)(rsp *protocol.CheckTokenResponse,err error){
func (s *AuthService) CheckToken(request *protocol.CheckTokenRequest) (rsp *protocol.CheckTokenResponse, err error) {
var (
userInfo *models.UserInfo
)
if len(request.Token)==0{
err = common.NewErrorWithMsg(4141,"token not empty")
if len(request.Token) == 0 {
err = common.NewErrorWithMsg(4141, "token not empty")
return
}
userInfo,err =models.GetUserInfoByToken(request.Token)
if err!=nil{
err =common.NewError(4141,err)
userInfo, err = models.GetUserInfoByToken(request.Token)
if err != nil {
err = common.NewError(4141, err)
return
}
rsp =&protocol.CheckTokenResponse{
UserInfo:userInfo,
IsValid:true,
rsp = &protocol.CheckTokenResponse{
UserInfo: userInfo,
IsValid: true,
}
return
}
//检查uuid 是否重复
func (s *AuthService)CheckUuid(request *protocol.CheckUuidRequest)(rsp *protocol.CheckUuidResponse,err error){
func (s *AuthService) CheckUuid(request *protocol.CheckUuidRequest) (rsp *protocol.CheckUuidResponse, err error) {
var (
logUuid *models.LogUuid
)
if len(request.Uuid)==0{
err = common.NewErrorWithMsg(4142,"uuid not empty")
if len(request.Uuid) == 0 {
err = common.NewErrorWithMsg(4142, "uuid not empty")
}
logUuid,err=models.GetLogUuidByUuid(request.Uuid)
if err==nil && logUuid!=nil{
err = common.NewErrorWithMsg(4142,"uuid not valid")
logUuid, err = models.GetLogUuidByUuid(request.Uuid)
if err == nil && logUuid != nil {
err = common.NewErrorWithMsg(4142, "uuid not valid")
}
models.AddLogUuid(&models.LogUuid{Uuid:request.Uuid})
rsp =&protocol.CheckUuidResponse{}
models.AddLogUuid(&models.LogUuid{Uuid: request.Uuid})
rsp = &protocol.CheckUuidResponse{}
return
}
//短信验证码 T
func (s *AuthService)SmsCode(request *protocol.SmsCodeRequest)(rsp *protocol.SmsCodeResponse,err error){
var(
value,key,msgContent string
smsInfo *protocol.SmsInfo
func (s *AuthService) SmsCode(request *protocol.SmsCodeRequest) (rsp *protocol.SmsCodeResponse, err error) {
var (
value, key, msgContent string
smsInfo *protocol.SmsInfo
)
msgContent = `【买买买信息科技】{{.Code}}({{.AppName}}手机验证码,请完成验证),如非本人操作,请忽略本短信`
switch request.SendType {
case protocol.SmsLoginCode:
case protocol.SmsChangeMobile:
default:
err = common.NewErrorWithMsg(2,"send_type error.")
err = common.NewErrorWithMsg(2, "send_type error.")
return
}
key = request.SendType
//check user phone exists
if !redis.Hexists(key,request.Phone){
if !redis.Hexists(key, request.Phone) {
smsInfo = &protocol.SmsInfo{
CreateTime:time.Now().Unix(),
CreateTime: time.Now().Unix(),
}
goto Send
}else{
if value,err =redis.Hget(key,request.Phone);err!=nil{
} else {
if value, err = redis.Hget(key, request.Phone); err != nil {
log.Error(err)
return
}
if err=json.Unmarshal([]byte(value),&smsInfo);err!=nil{
if err = json.Unmarshal([]byte(value), &smsInfo); err != nil {
log.Error(err)
return
}
//第二天重置
if smsInfo.LastTime<comm_time.GetUnixTimeByYyyymmdd(){
smsInfo.Count=0
if smsInfo.LastTime < comm_time.GetUnixTimeByYyyymmdd() {
smsInfo.Count = 0
smsInfo.CreateTime = time.Now().Unix()
}
if smsInfo.Count>100{//TODO:limit send time
if smsInfo.Count > 100 { //TODO:limit send time
return
}
goto Send
}
Send:
{
smsInfo.Code = common.RandomStringWithChars(6,string(protocol.Nums))
smsInfo.LastTime=time.Now().Unix()
smsInfo.ErrorCount =0
//Todo Lock
smsInfo.Count +=1
if err=redis.Hset(key,request.Phone,common.AssertJson(smsInfo),-1);err!=nil{
return
}
tp :=template.New("sms_code")
tp.Parse(msgContent)
buf :=bytes.NewBuffer(nil)
tp.Execute(
buf,
map[string]string{
"Code":smsInfo.Code,
"AppName":beego.BConfig.AppName,
},)
request.Content = buf.String()
err = sms.Send(request)
rsp = &protocol.SmsCodeResponse{
Code:smsInfo.Code,
}
Send:
{
smsInfo.Code = common.RandomStringWithChars(6, string(protocol.Nums))
smsInfo.LastTime = time.Now().Unix()
smsInfo.ErrorCount = 0
//Todo Lock
smsInfo.Count += 1
if err = redis.Hset(key, request.Phone, common.AssertJson(smsInfo), -1); err != nil {
return
}
tp := template.New("sms_code")
tp.Parse(msgContent)
buf := bytes.NewBuffer(nil)
tp.Execute(
buf,
map[string]string{
"Code": smsInfo.Code,
"AppName": beego.BConfig.AppName,
})
request.Content = buf.String()
err = sms.Send(request)
rsp = &protocol.SmsCodeResponse{
Code: smsInfo.Code,
}
}
return
}
//验证短信验证码 T
func CheckSmsCode(phone ,code ,sendType string)(result bool,err error){
var(
value string
func CheckSmsCode(phone, code, sendType string) (result bool, err error) {
var (
value string
smsInfo *protocol.SmsInfo
)
result =false
if value,err =redis.Hget(sendType,phone);err!=nil{//protocol.SmsLoginCode
err = common.NewErrorWithMsg(1009,"smscode expire")
result = false
if value, err = redis.Hget(sendType, phone); err != nil { //protocol.SmsLoginCode
err = common.NewErrorWithMsg(1009, "smscode expire")
return
}
if err=json.Unmarshal([]byte(value),&smsInfo);err!=nil{
if err = json.Unmarshal([]byte(value), &smsInfo); err != nil {
return
}
if smsInfo.ErrorCount>=5{
err = common.NewErrorWithMsg(1011,"smscode over error times")
if smsInfo.ErrorCount >= 5 {
err = common.NewErrorWithMsg(1011, "smscode over error times")
return
}
if (smsInfo.LastTime+60*5)<time.Now().Unix(){
err = common.NewErrorWithMsg(1009,fmt.Sprintf("smscode expire %v < %v",(smsInfo.LastTime+60*5),time.Now().Unix()))
if (smsInfo.LastTime + 60*5) < time.Now().Unix() {
err = common.NewErrorWithMsg(1009, fmt.Sprintf("smscode expire %v < %v", (smsInfo.LastTime+60*5), time.Now().Unix()))
goto Fail
}
if smsInfo.Code == code{
if smsInfo.Code == code {
result = true
return
}else{
err = common.NewErrorWithMsg(1012,"smscode error")
} else {
err = common.NewErrorWithMsg(1012, "smscode error")
goto Fail
}
Fail:
{
smsInfo.ErrorCount +=1
if err=redis.Hset(sendType,phone,common.AssertJson(smsInfo),-1);err!=nil{
return
}
Fail:
{
smsInfo.ErrorCount += 1
if err = redis.Hset(sendType, phone, common.AssertJson(smsInfo), -1); err != nil {
return
}
}
return
}
\ No newline at end of file
}
... ...
... ... @@ -3,35 +3,35 @@ package auth
import (
"testing"
"gitlab.fjmaimaimai.com/mmm-go/ability/protocol"
"gitlab.fjmaimaimai.com/mmm-go/ability/tests"
"ability/protocol"
"ability/tests"
)
func init(){
func init() {
tests.Init()
}
func Test_SmsCode(t *testing.T){
func Test_SmsCode(t *testing.T) {
var (
resp *protocol.SmsCodeResponse
err error
out bool
err error
out bool
)
input :=[]*protocol.SmsCodeRequest{
{Phone:"18860183051",SendType:"sms_login_code"},
{Phone:"18860183052",SendType:"sms_login_code"},
{Phone:"18860183052",SendType:"sms_login_code"},
{Phone:"18860183053",SendType:"sms_change_mobile"},
{Phone:"18860183053",SendType:"sms_change_mobile"},
{Phone:"18860183054",SendType:"sms_change_mobile"},
input := []*protocol.SmsCodeRequest{
{Phone: "18860183051", SendType: "sms_login_code"},
{Phone: "18860183052", SendType: "sms_login_code"},
{Phone: "18860183052", SendType: "sms_login_code"},
{Phone: "18860183053", SendType: "sms_change_mobile"},
{Phone: "18860183053", SendType: "sms_change_mobile"},
{Phone: "18860183054", SendType: "sms_change_mobile"},
}
var s IAuthService = &AuthService{}
for i:=range input{
if resp,err =s.SmsCode(input[i]);err!=nil{
t.Fatal("send sms code error. input:",input[i],err)
for i := range input {
if resp, err = s.SmsCode(input[i]); err != nil {
t.Fatal("send sms code error. input:", input[i], err)
}
if out,err =CheckSmsCode(input[i].Phone,resp.Code,input[i].SendType);err!=nil || !out{
t.Fatal("check sms code error.",input[i].Phone,input[i].SendType,resp.Code,err)
if out, err = CheckSmsCode(input[i].Phone, resp.Code, input[i].SendType); err != nil || !out {
t.Fatal("check sms code error.", input[i].Phone, input[i].SendType, resp.Code, err)
}
}
}
... ...
package sms
import (
"gitlab.fjmaimaimai.com/mmm-go/ability/protocol"
"ability/protocol"
"github.com/astaxie/beego"
"github.com/astaxie/beego/httplib"
... ... @@ -10,44 +10,44 @@ import (
)
type ISmsService interface {
Send(request *protocol.SmsCodeRequest)(err error)
Send(request *protocol.SmsCodeRequest) (err error)
}
type YunPianSmsService struct {}
type YunPianSmsService struct{}
func assertImplement(){
func assertImplement() {
var _ ISmsService = (*YunPianSmsService)(nil)
}
//发送
//发送
func(s *YunPianSmsService)Send(request *protocol.SmsCodeRequest)(err error){
func (s *YunPianSmsService) Send(request *protocol.SmsCodeRequest) (err error) {
var (
resp *YunPianResponse
)
log.Debug("[sms] mobile:",request.Phone," content:",request.Content)
if beego.BConfig.RunMode!="prod"{
log.Debug("[sms] mobile:", request.Phone, " content:", request.Content)
if beego.BConfig.RunMode != "prod" {
return
}
post:= httplib.Post(beego.AppConfig.String("yunpian_sms_sdk_url"))
post.Param("apikey",beego.AppConfig.String("yunpian_app_key"))
post.Param("mobile",request.Phone)
post.Param("text",request.Content)
if err= post.ToJSON(&resp);err!=nil{
post := httplib.Post(beego.AppConfig.String("yunpian_sms_sdk_url"))
post.Param("apikey", beego.AppConfig.String("yunpian_app_key"))
post.Param("mobile", request.Phone)
post.Param("text", request.Content)
if err = post.ToJSON(&resp); err != nil {
return
}
if resp.Code!=0 || resp.Mobile!=request.Phone{
log.Error("yunpian send sms code:",resp.Code," error msg:",resp.Msg)
err = common.NewErrorWithMsg(1,resp.Msg)
if resp.Code != 0 || resp.Mobile != request.Phone {
log.Error("yunpian send sms code:", resp.Code, " error msg:", resp.Msg)
err = common.NewErrorWithMsg(1, resp.Msg)
}
return nil
}
type YunPianResponse struct {
Code int `json:"code"` //0代表发送成功,其他code代表出错,详细见"返回值说明"页面
Msg string `json:"msg"`//例如""发送成功"",或者相应错误信息
Count int `json:"count"`//发送成功短信的计费条数(计费条数:70个字一条,超出70个字时按每67字一条计费)
Mobile string `json:"string"`//发送手机号
Fee float64 `json:"fee"` //扣费金额,单位:元,类型:双精度浮点型/double
Sid int64 `json:"sid"` //短信id,64位整型
}
\ No newline at end of file
Code int `json:"code"` //0代表发送成功,其他code代表出错,详细见"返回值说明"页面
Msg string `json:"msg"` //例如""发送成功"",或者相应错误信息
Count int `json:"count"` //发送成功短信的计费条数(计费条数:70个字一条,超出70个字时按每67字一条计费)
Mobile string `json:"string"` //发送手机号
Fee float64 `json:"fee"` //扣费金额,单位:元,类型:双精度浮点型/double
Sid int64 `json:"sid"` //短信id,64位整型
}
... ...
... ... @@ -9,7 +9,7 @@ import (
"path/filepath"
"time"
"gitlab.fjmaimaimai.com/mmm-go/ability/protocol"
"ability/protocol"
"github.com/astaxie/beego"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
... ... @@ -18,16 +18,14 @@ import (
)
//上传图片
func Image(request *protocol.FileRequest)(rsp *protocol.FileResponse,err error){
var (
)
for i:=range request.Files{
f :=request.Files[i]
subfix:=path.Ext(f.Filename)
func Image(request *protocol.FileRequest) (rsp *protocol.FileResponse, err error) {
var ()
for i := range request.Files {
f := request.Files[i]
subfix := path.Ext(f.Filename)
//文件格式不符合
if !(subfix==".jpg" || subfix==".gif" || subfix==".png"){
err = common.NewErrorWithMsg(2,"file format error")
if !(subfix == ".jpg" || subfix == ".gif" || subfix == ".png") {
err = common.NewErrorWithMsg(2, "file format error")
return
}
}
... ... @@ -35,57 +33,55 @@ func Image(request *protocol.FileRequest)(rsp *protocol.FileResponse,err error){
return UploadFile(request)
}
func Voice(request *protocol.FileRequest)(rsp *protocol.FileResponse,err error){
var (
)
func Voice(request *protocol.FileRequest) (rsp *protocol.FileResponse, err error) {
var ()
request.FileType = protocol.FileVoice
return UploadFile(request)
}
func UploadFile(request *protocol.FileRequest)(rsp *protocol.FileResponse,err error){
if request.FileType==""{
request.FileType =protocol.FileImage
func UploadFile(request *protocol.FileRequest) (rsp *protocol.FileResponse, err error) {
if request.FileType == "" {
request.FileType = protocol.FileImage
}
var (
src multipart.File
dst *os.File
virtualPath string = beego.AppConfig.String("source_virtual_path") //虚拟路径
sourcePath string = filepath.Join(beego.AppConfig.String("source_path"),request.FileType) //真实路径
date,filename string
src multipart.File
dst *os.File
virtualPath string = beego.AppConfig.String("source_virtual_path") //虚拟路径
sourcePath string = filepath.Join(beego.AppConfig.String("source_path"), request.FileType) //真实路径
date, filename string
)
rsp =&protocol.FileResponse{}
date =comm_time.GetTimeByYyyymmdd()
sourcePath = filepath.Join(sourcePath,date)
if _,err=os.Stat(sourcePath);err!=nil{
rsp = &protocol.FileResponse{}
date = comm_time.GetTimeByYyyymmdd()
sourcePath = filepath.Join(sourcePath, date)
if _, err = os.Stat(sourcePath); err != nil {
log.Error(err)
if err=os.MkdirAll(sourcePath,0777);err!=nil{
if err = os.MkdirAll(sourcePath, 0777); err != nil {
log.Error(err)
return
}
}
virtualPath=beego.AppConfig.String("source_host")+filepath.Join(virtualPath,request.FileType,date)
for i:=range request.Files{
f :=request.Files[i]
subfix:=path.Ext(f.Filename)
filename =fmt.Sprintf("%v_%v%v",time.Now().Unix(),common.RandomString(32),subfix)
src,err=f.Open()
if err!=nil{
virtualPath = beego.AppConfig.String("source_host") + filepath.Join(virtualPath, request.FileType, date)
for i := range request.Files {
f := request.Files[i]
subfix := path.Ext(f.Filename)
filename = fmt.Sprintf("%v_%v%v", time.Now().Unix(), common.RandomString(32), subfix)
src, err = f.Open()
if err != nil {
log.Error(err)
return
}
defer src.Close()
dst,err =os.OpenFile(filepath.Join(sourcePath,filename), os.O_RDWR | os.O_CREATE |os.O_TRUNC,0777) //file/ab/ 静态文件目录
if err!=nil{
dst, err = os.OpenFile(filepath.Join(sourcePath, filename), os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0777) //file/ab/ 静态文件目录
if err != nil {
log.Error(err)
return
}
defer dst.Close()
if _,err =io.Copy(dst,src);err!=nil{
if _, err = io.Copy(dst, src); err != nil {
log.Error(err)
return
}
rsp.Paths = append(rsp.Paths,filepath.Join(virtualPath,filename))
rsp.Paths = append(rsp.Paths, filepath.Join(virtualPath, filename))
}
return
}
\ No newline at end of file
}
... ...
package upload
import (
"testing"
"mime/multipart"
"bytes"
"mime/multipart"
"testing"
"gitlab.fjmaimaimai.com/mmm-go/ability/protocol"
"gitlab.fjmaimaimai.com/mmm-go/ability/tests"
"ability/protocol"
"ability/tests"
)
func init(){
func init() {
tests.Init()
}
func Test_Image(t *testing.T){
func Test_Image(t *testing.T) {
input := &protocol.FileRequest{}
var bufReader bytes.Buffer
mpWriter:=multipart.NewWriter(&bufReader)
fw,err :=mpWriter.CreateFormFile("file_a","a.jpg")//a.txt
if err!=nil{
mpWriter := multipart.NewWriter(&bufReader)
fw, err := mpWriter.CreateFormFile("file_a", "a.jpg") //a.txt
if err != nil {
t.Fatal(err)
return
}
fw.Write([]byte("this is a txt"))
mpWriter.WriteField("name","tiprok")
mpWriter.WriteField("name", "tiprok")
fwb,err :=mpWriter.CreateFormFile("file_a","b.png")
if err!=nil{
fwb, err := mpWriter.CreateFormFile("file_a", "b.png")
if err != nil {
t.Fatal(err)
return
}
fwb.Write([]byte("this is b txt"))
mpWriter.Close()
mpReader:=multipart.NewReader(&bufReader,mpWriter.Boundary())
form,err :=mpReader.ReadForm(100)
if err!=nil{
mpReader := multipart.NewReader(&bufReader, mpWriter.Boundary())
form, err := mpReader.ReadForm(100)
if err != nil {
t.Fatal(err)
}
for _,files :=range form.File{
for _, files := range form.File {
//for i:=range files{
// file :=files[i]
// if f,err :=file.Open();err!=nil{
... ... @@ -53,11 +51,11 @@ func Test_Image(t *testing.T){
//
// }
//}
input.Files = append(input.Files,files...)
input.Files = append(input.Files, files...)
}
rsp,err :=Image(input)
if err!=nil{
rsp, err := Image(input)
if err != nil {
t.Fatal(err)
}
t.Log(rsp)
... ...
... ... @@ -4,7 +4,7 @@ package user
//(
// "gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/mybeego"
// "gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
// "gitlab.fjmaimaimai.com/mmm-go/ability/models"
// "ability/models"
//)
//
//func GetUserList(mobile string)*mybeego.Message{
... ...
... ... @@ -3,37 +3,38 @@ package version
import (
"strconv"
"gitlab.fjmaimaimai.com/mmm-go/ability/models"
"gitlab.fjmaimaimai.com/mmm-go/ability/protocol"
"ability/models"
"ability/protocol"
)
func GetLatestVersionInfo(request *protocol.GetLatestVersionInfoRequest)(rsp *protocol.GetLatestVersionInfoResponse,err error){
func GetLatestVersionInfo(request *protocol.GetLatestVersionInfoRequest) (rsp *protocol.GetLatestVersionInfoResponse, err error) {
var (
versionInfo *protocol.VersionInfo
)
versionInfo,err = GetVersionInfo(request.VersionNo,request.Channel)
if err!=nil{
versionInfo, err = GetVersionInfo(request.VersionNo, request.Channel)
if err != nil {
return
}
rsp =&protocol.GetLatestVersionInfoResponse{
Version:versionInfo,
rsp = &protocol.GetLatestVersionInfoResponse{
Version: versionInfo,
}
return
}
//获取版本信息
func GetVersionInfo(versionNo,channel int)(v *protocol.VersionInfo,err error){
cfgAppVersion,err :=models.GetCfgAppVersion(versionNo,channel)
if err!=nil{
func GetVersionInfo(versionNo, channel int) (v *protocol.VersionInfo, err error) {
cfgAppVersion, err := models.GetCfgAppVersion(versionNo, channel)
if err != nil {
return
}
v =&protocol.VersionInfo{
VersionName:cfgAppVersion.VersionName,
VersionNo:strconv.Itoa(cfgAppVersion.VersionNo),
Title:cfgAppVersion.Title,
Content:cfgAppVersion.Content,
DownloadPage:cfgAppVersion.DownloadPage,
DownloadFile:cfgAppVersion.DownloadFile,
UpdateType:cfgAppVersion.Type,
v = &protocol.VersionInfo{
VersionName: cfgAppVersion.VersionName,
VersionNo: strconv.Itoa(cfgAppVersion.VersionNo),
Title: cfgAppVersion.Title,
Content: cfgAppVersion.Content,
DownloadPage: cfgAppVersion.DownloadPage,
DownloadFile: cfgAppVersion.DownloadFile,
UpdateType: cfgAppVersion.Type,
}
return
}
\ No newline at end of file
}
... ...
package tests
import (
"ability/protocol"
"github.com/astaxie/beego"
_ "github.com/go-sql-driver/mysql"
"gitlab.fjmaimaimai.com/mmm-go/ability/protocol"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/config"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/orm"
... ... @@ -16,28 +16,28 @@ import (
var one sync.Once
func Init(){
one.Do(func(){
func Init() {
one.Do(func() {
_, file, _, _ := runtime.Caller(0)
apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".." + string(filepath.Separator))))
apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".."+string(filepath.Separator))))
beego.TestBeegoInit(apppath)
path,_:=os.Getwd()
filename :="app.conf"
path, _ := os.Getwd()
filename := "app.conf"
beego.LoadAppConfig("ini", filepath.Join(path, "conf", filename))
log.InitLog(config.Logger{
Filename:"app.log",
Level:"3", //7
Filename: "app.log",
Level: "3", //7
})
err:= redis.InitWithDb(100,beego.AppConfig.String("redis_add_port"),beego.AppConfig.String("redis_auth"),"0")
if err!=nil{
err := redis.InitWithDb(100, beego.AppConfig.String("redis_add_port"), beego.AppConfig.String("redis_auth"), "0")
if err != nil {
log.Fatal(err)
panic(err)
}
orm.NewBeeormEngine(config.Mysql{
DataSource:beego.AppConfig.String("data_source"),
MaxIdle: 100,
MaxOpen:100,
DataSource: beego.AppConfig.String("data_source"),
MaxIdle: 100,
MaxOpen: 100,
})
protocol.InitMessageCode()
})
... ...
... ... @@ -6,7 +6,7 @@ package tests
// "testing"
// "runtime"
// "path/filepath"
// _ "gitlab.fjmaimaimai.com/mmm-go/ability/routers"
// _ "ability/routers"
//
// "github.com/astaxie/beego"
// . "github.com/smartystreets/goconvey/convey"
... ... @@ -36,4 +36,3 @@ package tests
// })
// })
//}
... ...