公司pc的代码merge
parent
974c3d6fc8
commit
bc2de61c4d
|
@ -1,2 +1,3 @@
|
|||
glide.yaml
|
||||
api_user.exe
|
||||
user.exe
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"log"
|
||||
"gopkg.in/yaml.v2"
|
||||
"log"
|
||||
"os"
|
||||
"runtime"
|
||||
)
|
||||
|
@ -12,14 +12,14 @@ var ostype = runtime.GOOS
|
|||
var conf ConfAPI
|
||||
|
||||
type ConfAPI struct {
|
||||
ListenSvr int `yaml:"listen_svr"` // 服务监听端口
|
||||
ListenApi int `yaml:"listen_api"` // 服务监听端口
|
||||
RunMode string `yaml:"runmode"` // 服务运行模式
|
||||
MaxConn int `yaml:"max_conn"`
|
||||
Logs LogConfig `yaml:"logs"` // 日志
|
||||
Redis1 EntityRedis `yaml:"redis1"`
|
||||
Mysql MysqlConfig `yaml:"mysql"` // 认证配置
|
||||
init bool
|
||||
ListenSvr int `yaml:"listen_svr"` // 服务监听端口
|
||||
ListenApi int `yaml:"listen_api"` // 服务监听端口
|
||||
RunMode string `yaml:"runmode"` // 服务运行模式
|
||||
MaxConn int `yaml:"max_conn"`
|
||||
Logs LogConfig `yaml:"logs"` // 日志
|
||||
Redis1 EntityRedis `yaml:"redis1"`
|
||||
Mysql MysqlConfig `yaml:"mysql"` // 认证配置
|
||||
init bool
|
||||
}
|
||||
|
||||
type EntityRedis struct {
|
||||
|
@ -47,18 +47,20 @@ type MysqlConfig struct {
|
|||
MaxOpen int `yaml:"max_open"`
|
||||
MaxIdle int `yaml:"max_idle"`
|
||||
}
|
||||
|
||||
var gConf ConfAPI
|
||||
|
||||
func Init(path string) error {
|
||||
file,e := os.Open(path)
|
||||
if nil != e{
|
||||
file, e := os.Open(path)
|
||||
if nil != e {
|
||||
log.Println(e.Error())
|
||||
return e
|
||||
}
|
||||
stat,_ := file.Stat()
|
||||
filec := make([]byte, stat.Size())
|
||||
stat, _ := file.Stat()
|
||||
filec := make([]byte, stat.Size())
|
||||
file.Read(filec)
|
||||
e = yaml.Unmarshal(filec,&gConf)
|
||||
if nil != e{
|
||||
e = yaml.Unmarshal(filec, &gConf)
|
||||
if nil != e {
|
||||
log.Println(e.Error())
|
||||
}
|
||||
gConf.init = true
|
||||
|
@ -66,30 +68,30 @@ func Init(path string) error {
|
|||
}
|
||||
|
||||
func GetPort() int {
|
||||
if gConf.init{
|
||||
if gConf.init {
|
||||
return gConf.ListenApi
|
||||
}else {
|
||||
return 8001
|
||||
} else {
|
||||
return 8001
|
||||
}
|
||||
}
|
||||
func GetMysqlConfig() *MysqlConfig{
|
||||
if gConf.init{
|
||||
func GetMysqlConfig() *MysqlConfig {
|
||||
if gConf.init {
|
||||
return &gConf.Mysql
|
||||
}else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
func GetRedis1() *EntityRedis {
|
||||
if gConf.init{
|
||||
return &gConf.Redis1
|
||||
}else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
func GetLogConfig() *LogConfig {
|
||||
if gConf.init{
|
||||
return &gConf.Logs
|
||||
}else{
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
func GetRedis1() *EntityRedis {
|
||||
if gConf.init {
|
||||
return &gConf.Redis1
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
func GetLogConfig() *LogConfig {
|
||||
if gConf.init {
|
||||
return &gConf.Logs
|
||||
} else {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
|
|
@ -31,12 +31,12 @@ func initRedis(addr string, pwd string, db int, coon int) (*redis.Client, error)
|
|||
|
||||
func InitRedis() error {
|
||||
redisConf := GetRedis1()
|
||||
if nil == redisConf{
|
||||
if nil == redisConf {
|
||||
return errors.New("Error Config Redis")
|
||||
}else {
|
||||
} else {
|
||||
var e error
|
||||
gRedis1,e = initRedis(GetRedis1().Addr,GetRedis1().Pwd,GetRedis1().DB,GetRedis1().PoolSize)
|
||||
if nil != e{
|
||||
gRedis1, e = initRedis(GetRedis1().Addr, GetRedis1().Pwd, GetRedis1().DB, GetRedis1().PoolSize)
|
||||
if nil != e {
|
||||
logs.Error(e.Error())
|
||||
return e
|
||||
}
|
||||
|
@ -45,4 +45,4 @@ func InitRedis() error {
|
|||
}
|
||||
func RedisOne() *redis.Client {
|
||||
return gRedis1
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,21 +1,21 @@
|
|||
package _const
|
||||
|
||||
var RespCode map[int]string
|
||||
var RespCode map[int]string
|
||||
|
||||
const (
|
||||
RESP_ERR_COMON = 101
|
||||
RESP_ERR_OK = 0
|
||||
RESP_ERR_OK = 0
|
||||
)
|
||||
|
||||
func init() {
|
||||
func init() {
|
||||
RespCode[RESP_ERR_OK] = "OK"
|
||||
RespCode[RESP_ERR_COMON] = "Err"
|
||||
}
|
||||
func M(key int) string{
|
||||
v,ok := RespCode[key]
|
||||
if ok{
|
||||
func M(key int) string {
|
||||
v, ok := RespCode[key]
|
||||
if ok {
|
||||
return v
|
||||
}else {
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -27,28 +27,28 @@ import (
|
|||
)
|
||||
|
||||
type ReqSendEmailCode struct {
|
||||
EmailAdress string `json:"email_address"`
|
||||
EmailAdress string `json:"email_address"`
|
||||
}
|
||||
|
||||
type SetUserGroupReq struct {
|
||||
Id int64 `json:"id,omitempty"`
|
||||
Id int64 `json:"id,omitempty"`
|
||||
Description string `json:"description"`
|
||||
GroupName string `json:"group_name"`
|
||||
UserIds []int `json:"user_ids"`
|
||||
GroupName string `json:"group_name"`
|
||||
UserIds []int `json:"user_ids"`
|
||||
}
|
||||
type RespBase struct {
|
||||
Msg string
|
||||
Msg string
|
||||
Status int
|
||||
Data interface{}
|
||||
Data interface{}
|
||||
}
|
||||
|
||||
func Auth(c *gin.Context) {
|
||||
func Auth(c *gin.Context) {
|
||||
var resp RespBase
|
||||
var statuscode int
|
||||
|
||||
statuscode = 200
|
||||
|
||||
var userinfo map[string] interface{}
|
||||
var userinfo map[string]interface{}
|
||||
//var userSockToken map[string] interface{}
|
||||
|
||||
defer func() {
|
||||
|
@ -56,19 +56,20 @@ func Auth(c *gin.Context) {
|
|||
}()
|
||||
|
||||
socketToken := c.Query("socketToken")
|
||||
struserinfo ,e := redis.Get(socketToken)
|
||||
struserinfo, e := redis.Get(socketToken)
|
||||
|
||||
if e != nil{
|
||||
if e != nil {
|
||||
logs.Error(e.Error())
|
||||
return
|
||||
}
|
||||
|
||||
e = json.Unmarshal([]byte(struserinfo),userinfo)
|
||||
if nil != e{
|
||||
e = json.Unmarshal([]byte(struserinfo), userinfo)
|
||||
if nil != e {
|
||||
logs.Error(e.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// SetUser godoc
|
||||
// @Summary SetUser
|
||||
// @Description set userinfo
|
||||
|
@ -77,10 +78,10 @@ func Auth(c *gin.Context) {
|
|||
// @Param q query string false "name search by q"
|
||||
// @Success 200 {array} util.RespBase
|
||||
// @Router /accounts [get]
|
||||
func SetUser(c *gin.Context){
|
||||
func SetUser(c *gin.Context) {
|
||||
|
||||
}
|
||||
func DelUser(c *gin.Context){
|
||||
func DelUser(c *gin.Context) {
|
||||
|
||||
}
|
||||
|
||||
|
@ -89,25 +90,26 @@ func GetUser(c *gin.Context) {
|
|||
resp.Msg = "操作失败"
|
||||
resp.Status = 20
|
||||
defer func() {
|
||||
c.JSON(200,resp)
|
||||
c.JSON(200, resp)
|
||||
}()
|
||||
session := sessions.Get(c)
|
||||
userinfo := session.Get("")
|
||||
if userinfo == nil{
|
||||
if userinfo == nil {
|
||||
logs.Error("error could not find key")
|
||||
return
|
||||
}
|
||||
var users map[string] interface{}
|
||||
e := json.Unmarshal([]byte(userinfo.(string)),&users)
|
||||
var users map[string]interface{}
|
||||
e := json.Unmarshal([]byte(userinfo.(string)), &users)
|
||||
if nil != e {
|
||||
logs.Error(e.Error())
|
||||
}
|
||||
delete(users,"socketToken" +
|
||||
delete(users, "socketToken"+
|
||||
"")
|
||||
resp.Status = 0
|
||||
resp.Msg = "操作成功"
|
||||
resp.Data = users
|
||||
}
|
||||
|
||||
// GetUsers godoc
|
||||
// @Summary GetUsers
|
||||
// @Description Get all user with query
|
||||
|
@ -127,23 +129,23 @@ func Users(c *gin.Context) {
|
|||
resp.Status = 0
|
||||
statuscode = 200
|
||||
defer func() {
|
||||
c.JSON(statuscode,resp)
|
||||
c.JSON(statuscode, resp)
|
||||
}()
|
||||
offset := c.Query("offset")
|
||||
limit := c.Query("limit")
|
||||
ioffset,e := strconv.Atoi(offset)
|
||||
if nil != e{
|
||||
ioffset, e := strconv.Atoi(offset)
|
||||
if nil != e {
|
||||
logs.Error(e.Error())
|
||||
return
|
||||
}
|
||||
ilimit,er := strconv.Atoi(limit)
|
||||
if nil != er{
|
||||
ilimit, er := strconv.Atoi(limit)
|
||||
if nil != er {
|
||||
logs.Error(e.Error())
|
||||
return
|
||||
}
|
||||
|
||||
dat := map[string] interface{}{}
|
||||
users,all := model.GetUsers(int32(ilimit),int32(ioffset),"")
|
||||
dat := map[string]interface{}{}
|
||||
users, all := model.GetUsers(int32(ilimit), int32(ioffset), "")
|
||||
dat["users"] = users
|
||||
dat["all"] = all
|
||||
resp.Msg = "OK"
|
||||
|
@ -169,70 +171,72 @@ func SerarchUsers(c *gin.Context) {
|
|||
resp.Status = 0
|
||||
statuscode = 200
|
||||
defer func() {
|
||||
c.JSON(statuscode,resp)
|
||||
c.JSON(statuscode, resp)
|
||||
}()
|
||||
offset := c.Query("offset")
|
||||
limit := c.Query("limit")
|
||||
username := c.PostForm("username")
|
||||
ioffset,e := strconv.Atoi(offset)
|
||||
if nil != e{
|
||||
ioffset, e := strconv.Atoi(offset)
|
||||
if nil != e {
|
||||
logs.Error(e.Error())
|
||||
return
|
||||
}
|
||||
ilimit,er := strconv.Atoi(limit)
|
||||
if nil != er{
|
||||
ilimit, er := strconv.Atoi(limit)
|
||||
if nil != er {
|
||||
logs.Error(e.Error())
|
||||
return
|
||||
}
|
||||
|
||||
dat := map[string] interface{}{}
|
||||
users,all := model.GetUsers(int32(ilimit),int32(ioffset),username)
|
||||
dat := map[string]interface{}{}
|
||||
users, all := model.GetUsers(int32(ilimit), int32(ioffset), username)
|
||||
dat["users"] = users
|
||||
dat["all"] = all
|
||||
resp.Msg = "OK"
|
||||
resp.Data = dat
|
||||
}
|
||||
func CreateVerify(length int32) string{
|
||||
strAry := []byte{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
|
||||
func CreateVerify(length int32) string {
|
||||
strAry := []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}
|
||||
result := string("")
|
||||
for i := int32(0); i < length; i++ {
|
||||
x := rand.Intn(len(strAry))
|
||||
result += string(strAry[x])
|
||||
}
|
||||
return result
|
||||
}
|
||||
/**
|
||||
* 取随机Token
|
||||
* @param {Number} length 取Token的长度
|
||||
* @return {string} 获取的Token
|
||||
*/
|
||||
func createToken(length int32) string{
|
||||
strAry := []byte{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_' };
|
||||
result := string("")
|
||||
for i := int32(0); i < length; i++ {
|
||||
for i := int32(0); i < length; i++ {
|
||||
x := rand.Intn(len(strAry))
|
||||
result += string(strAry[x])
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ByteSliceToString(b []byte) string {
|
||||
/**
|
||||
* 取随机Token
|
||||
* @param {Number} length 取Token的长度
|
||||
* @return {string} 获取的Token
|
||||
*/
|
||||
func createToken(length int32) string {
|
||||
strAry := []byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '_'}
|
||||
result := string("")
|
||||
for i := int32(0); i < length; i++ {
|
||||
x := rand.Intn(len(strAry))
|
||||
result += string(strAry[x])
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func ByteSliceToString(b []byte) string {
|
||||
var ret string
|
||||
|
||||
for i := 0;i < len(b) ;i++{
|
||||
s := fmt.Sprintf("%02x",b[i])
|
||||
for i := 0; i < len(b); i++ {
|
||||
s := fmt.Sprintf("%02x", b[i])
|
||||
ret += string(s)
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func DefaultOption(c *gin.Context) {
|
||||
func DefaultOption(c *gin.Context) {
|
||||
var resp RespBase
|
||||
|
||||
defer func() {
|
||||
c.JSON(204, resp)
|
||||
}()
|
||||
}
|
||||
|
||||
// Login godoc
|
||||
// @Summary Login
|
||||
// @Description login
|
||||
|
@ -244,11 +248,11 @@ func DefaultOption(c *gin.Context) {
|
|||
// @Failure 404 {object} util.RespBase
|
||||
// @Failure 500 {object} util.RespBase
|
||||
// @Router /api/login [post]
|
||||
func Login(c *gin.Context) {
|
||||
func Login(c *gin.Context) {
|
||||
type LoginReq struct {
|
||||
RememberMe int32 `json:"remember_me"`
|
||||
UserName string `json:"user_name"`
|
||||
UserPwd string `json:"user_pwd"`
|
||||
RememberMe int32 `json:"remember_me"`
|
||||
UserName string `json:"user_name"`
|
||||
UserPwd string `json:"user_pwd"`
|
||||
}
|
||||
var req LoginReq
|
||||
statusCode := 200
|
||||
|
@ -258,7 +262,7 @@ func Login(c *gin.Context) {
|
|||
c.JSON(statusCode, resp)
|
||||
}()
|
||||
e := c.Bind(&req)
|
||||
if e!= nil{
|
||||
if e != nil {
|
||||
log.Println(e.Error())
|
||||
return
|
||||
}
|
||||
|
@ -269,8 +273,8 @@ func Login(c *gin.Context) {
|
|||
var result []model.Users
|
||||
|
||||
er := db.GetMysqlClient().Query2("select * from users where user_name = ?",
|
||||
&result,req.UserName)
|
||||
if nil != er{
|
||||
&result, req.UserName)
|
||||
if nil != er {
|
||||
log.Println(er.Error())
|
||||
}
|
||||
strpassmd5 := ByteSliceToString(passmd5)
|
||||
|
@ -280,26 +284,26 @@ func Login(c *gin.Context) {
|
|||
socketToken.Write([]byte(createToken(6))) // 需要加密的字符串为 123456
|
||||
socketTokenMd5 := socketToken.Sum(nil)
|
||||
m := structs.Map(result[0])
|
||||
m["socketToken"] = ByteSliceToString(socketTokenMd5);
|
||||
sessionInfo,err := json.Marshal(m)
|
||||
if err != nil{
|
||||
m["socketToken"] = ByteSliceToString(socketTokenMd5)
|
||||
sessionInfo, err := json.Marshal(m)
|
||||
if err != nil {
|
||||
log.Println(err.Error())
|
||||
}
|
||||
if req.RememberMe == 1{
|
||||
config.RedisOne().Set(string(socketTokenMd5),string(sessionInfo),time.Second *2 * 24 * 3600 * 1000 )
|
||||
}else {
|
||||
config.RedisOne().Set(string(socketTokenMd5),string(sessionInfo),time.Second *8 * 3600 * 1000 )
|
||||
if req.RememberMe == 1 {
|
||||
config.RedisOne().Set(string(socketTokenMd5), string(sessionInfo), time.Second*2*24*3600*1000)
|
||||
} else {
|
||||
config.RedisOne().Set(string(socketTokenMd5), string(sessionInfo), time.Second*8*3600*1000)
|
||||
}
|
||||
//存储session
|
||||
session := sessions.Get(c)
|
||||
session.Set("",string(sessionInfo))
|
||||
session.Set("", string(sessionInfo))
|
||||
//session.
|
||||
var Options *sessions.Options
|
||||
if req.RememberMe == 1{
|
||||
if req.RememberMe == 1 {
|
||||
Options = &sessions.Options{
|
||||
MaxAge: 2 * 24 * 3600 * 1000,
|
||||
}
|
||||
}else {
|
||||
} else {
|
||||
Options = &sessions.Options{
|
||||
MaxAge: 8 * 3600 * 1000,
|
||||
}
|
||||
|
@ -310,23 +314,23 @@ func Login(c *gin.Context) {
|
|||
resp.Msg = "登录成功"
|
||||
resp.Status = 0
|
||||
resp.Data = string(sessionInfo)
|
||||
}else {
|
||||
} else {
|
||||
resp.Status = 422
|
||||
resp.Msg = "用户密码不正确"
|
||||
}
|
||||
}else {
|
||||
} else {
|
||||
resp.Status = 422
|
||||
resp.Msg = "登录账号不存在,请重新输入"
|
||||
}
|
||||
}
|
||||
|
||||
func Register(c *gin.Context) {
|
||||
func Register(c *gin.Context) {
|
||||
type RegisterReq struct {
|
||||
DisplayName string `json:"display_name"`
|
||||
EmailAdress string `json:"email_address"`
|
||||
EmailCode string `json:"email_code"`
|
||||
UserName string `json:"user_name"`
|
||||
UserPwd string `json:"user_pwd"`
|
||||
EmailCode string `json:"email_code"`
|
||||
UserName string `json:"user_name"`
|
||||
UserPwd string `json:"user_pwd"`
|
||||
}
|
||||
var req RegisterReq
|
||||
statusCode := 200
|
||||
|
@ -341,14 +345,14 @@ func Register(c *gin.Context) {
|
|||
}()
|
||||
|
||||
e := c.Bind(&req)
|
||||
if e!= nil{
|
||||
if e != nil {
|
||||
log.Println(e.Error())
|
||||
return
|
||||
}
|
||||
userKey := fmt.Sprintf("user_%s_verify",req.EmailAdress)
|
||||
userKey := fmt.Sprintf("user_%s_verify", req.EmailAdress)
|
||||
verify := config.RedisOne().Get(userKey).Val()
|
||||
|
||||
if verify != req.EmailCode{
|
||||
if verify != req.EmailCode {
|
||||
resp.Msg = "验证码错误"
|
||||
resp.Status = 20
|
||||
return
|
||||
|
@ -369,28 +373,28 @@ func Register(c *gin.Context) {
|
|||
var result []model.Users
|
||||
|
||||
er := db.GetMysqlClient().Query2("select * from users where user_name = ?",
|
||||
&result,req.UserName)
|
||||
if nil != er{
|
||||
&result, req.UserName)
|
||||
if nil != er {
|
||||
log.Println(er.Error())
|
||||
return
|
||||
}
|
||||
if len(result) > 0{
|
||||
if len(result) > 0 {
|
||||
resp.Msg = "失败,账号已经存在"
|
||||
resp.Status = 20
|
||||
return
|
||||
}
|
||||
query := fmt.Sprintf("insert into users(user_name,user_pwd,created_date," +
|
||||
"updated_date,display_name,email_address) values ('%s','%s','%s','%s','%s','%s') ",user.UserName,user.UserPwd,user.CreatedDate,user.UpdatedDate,
|
||||
user.DisplayName,user.EmailAddress)
|
||||
n,er := db.GetMysqlClient().Insert(query)
|
||||
if n == 0 || n < 0{
|
||||
query := fmt.Sprintf("insert into users(user_name,user_pwd,created_date,"+
|
||||
"updated_date,display_name,email_address) values ('%s','%s','%s','%s','%s','%s') ", user.UserName, user.UserPwd, user.CreatedDate, user.UpdatedDate,
|
||||
user.DisplayName, user.EmailAddress)
|
||||
n, er := db.GetMysqlClient().Insert(query)
|
||||
if n == 0 || n < 0 {
|
||||
statusCode = 422
|
||||
logs.Error(er.Error())
|
||||
resp.Msg = "失败,账号已经存在"
|
||||
resp.Status = 20
|
||||
return
|
||||
}
|
||||
if nil != er{
|
||||
if nil != er {
|
||||
statusCode = 422
|
||||
logs.Error(er.Error())
|
||||
resp.Msg = "失败"
|
||||
|
@ -401,65 +405,64 @@ func Register(c *gin.Context) {
|
|||
resp.Status = 0
|
||||
}
|
||||
|
||||
func Logout(c *gin.Context) {
|
||||
func Logout(c *gin.Context) {
|
||||
var resp RespBase
|
||||
|
||||
resp.Msg = "退出成功"
|
||||
resp.Status = 0
|
||||
defer func() {
|
||||
c.JSON(200,resp)
|
||||
c.JSON(200, resp)
|
||||
}()
|
||||
session := sessions.Get(c)
|
||||
session.Delete("")
|
||||
session.Save()
|
||||
}
|
||||
|
||||
|
||||
func Reader2Json(r io.ReadCloser) string{
|
||||
func Reader2Json(r io.ReadCloser) string {
|
||||
var ret string
|
||||
for i := 0;;i++{
|
||||
s := make([]byte,10)
|
||||
_,e := r.Read(s)
|
||||
for i := 0; ; i++ {
|
||||
s := make([]byte, 10)
|
||||
_, e := r.Read(s)
|
||||
ret += string(s)
|
||||
if e != nil{
|
||||
if e != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return ret
|
||||
}
|
||||
|
||||
func SendExternalEmail(msg interface{}) error{
|
||||
req := make(map[string] interface{},1)
|
||||
func SendExternalEmail(msg interface{}) error {
|
||||
req := make(map[string]interface{}, 1)
|
||||
req["type"] = "text"
|
||||
req["action"] = "smtp-sys"
|
||||
req["apiType"] = "send"
|
||||
|
||||
content ,err := json.Marshal(msg)
|
||||
if err != nil{
|
||||
content, err := json.Marshal(msg)
|
||||
if err != nil {
|
||||
log.Println(err.Error())
|
||||
return errors.New("Json marshal error")
|
||||
}
|
||||
req["content"] = string(content)
|
||||
|
||||
var buffer bytes.Buffer
|
||||
b,e := json.Marshal(req)
|
||||
if e != nil{
|
||||
b, e := json.Marshal(req)
|
||||
if e != nil {
|
||||
log.Println(e.Error())
|
||||
}
|
||||
buffer.Write(b)
|
||||
resp,err := http.Post("http://47.93.230.163:8091/msg/v1/send","application/json",&buffer)
|
||||
resp, err := http.Post("http://47.93.230.163:8091/msg/v1/send", "application/json", &buffer)
|
||||
|
||||
if resp.StatusCode != 200{
|
||||
if resp.StatusCode != 200 {
|
||||
return errors.New("error send emain")
|
||||
}
|
||||
if err != nil{
|
||||
if err != nil {
|
||||
logs.Error("error send email")
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
return nil
|
||||
}
|
||||
|
||||
func SendToMail(title,user string, password string, host string, to string, content string,
|
||||
func SendToMail(title, user string, password string, host string, to string, content string,
|
||||
ifgenerate bool) error {
|
||||
var content_type string
|
||||
|
||||
|
@ -469,26 +472,26 @@ func SendToMail(title,user string, password string, host string, to string, cont
|
|||
content_type = "Content-Type: text/plain" + "; charset=UTF-8"
|
||||
|
||||
msg := []byte("To: " + to + "\r\nFrom: " + user + "\r\nSubject: " + title + "\r\n" +
|
||||
content_type + "\r\n\r\n"+ content + "\r\n" )
|
||||
content_type + "\r\n\r\n" + content + "\r\n")
|
||||
send_to := strings.Split(to, ";")
|
||||
|
||||
//检测是否是邮件地址
|
||||
for k,_ := range send_to{
|
||||
for k, _ := range send_to {
|
||||
match, _ := regexp.MatchString("[\\w!#$%&'*+/=?^_`{|}~-]+(?:\\.[\\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\\w](?:[\\w-]*[\\w])?\\.)+[\\w](?:[\\w-]*[\\w])?", send_to[k])
|
||||
if !match{
|
||||
if !match {
|
||||
return errors.New("Format Error")
|
||||
}
|
||||
}
|
||||
err := smtp.SendMail(host, auth, user,send_to, msg)
|
||||
if err !=nil{
|
||||
err := smtp.SendMail(host, auth, user, send_to, msg)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func SendEmailCode(c *gin.Context) {
|
||||
func SendEmailCode(c *gin.Context) {
|
||||
var req ReqSendEmailCode
|
||||
var resp RespBase = RespBase{Msg:"邮件已经存在",Status:0}
|
||||
var resp RespBase = RespBase{Msg: "邮件已经存在", Status: 0}
|
||||
statusCode := 200
|
||||
|
||||
defer func() {
|
||||
|
@ -496,34 +499,34 @@ func SendEmailCode(c *gin.Context) {
|
|||
}()
|
||||
|
||||
e := c.Bind(&req)
|
||||
if nil != e{
|
||||
if nil != e {
|
||||
log.Println(e.Error())
|
||||
resp.Msg = "请求参数错误"
|
||||
return
|
||||
}
|
||||
//判断邮箱是否存在
|
||||
var users []model.Users
|
||||
db.GetMysqlClient().Query2("select * from users where email_adress = ?",&users,req.EmailAdress)
|
||||
if len(users) != 0{
|
||||
db.GetMysqlClient().Query2("select * from users where email_adress = ?", &users, req.EmailAdress)
|
||||
if len(users) != 0 {
|
||||
statusCode = 422
|
||||
return
|
||||
}
|
||||
//产生验证码
|
||||
verify := CreateVerify(6)
|
||||
session := sessions.Get(c)
|
||||
session.Set(req.EmailAdress,verify)
|
||||
session.Set(req.EmailAdress, verify)
|
||||
|
||||
session.Save()
|
||||
sendcontent := make( map[string] interface{},1)
|
||||
sendcontent := make(map[string]interface{}, 1)
|
||||
sendcontent["subject"] = "邮箱验证码,请注意查收"
|
||||
sendcontent["receivers"] = req.EmailAdress
|
||||
sendcontent["content"] = string("您本次注册的验证码为:") + verify + string(",工作人员不会向您索取,请勿泄露。请尽快完成操作。")
|
||||
|
||||
e = SendExternalEmail(sendcontent)
|
||||
if e != nil{
|
||||
if e != nil {
|
||||
log.Println(e.Error())
|
||||
return
|
||||
}
|
||||
//成功
|
||||
resp.Msg = "发送成功"
|
||||
}
|
||||
}
|
||||
|
|
|
@ -14,8 +14,8 @@ import (
|
|||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
"user/controller"
|
||||
"user/config"
|
||||
"user/controller"
|
||||
"user/db"
|
||||
)
|
||||
|
||||
|
@ -63,9 +63,10 @@ type ReqSendEmailTpl struct {
|
|||
Generate bool `json:"generate"`
|
||||
}
|
||||
type ReqSendEmail struct {
|
||||
Email string `json:"email_address"`
|
||||
Email string `json:"email_address"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
func SendToMail(title, user, password, host, to, content string) error {
|
||||
var content_type string
|
||||
hp := strings.Split(host, ":")
|
||||
|
@ -90,7 +91,6 @@ func SendToMail(title, user, password, host, to, content string) error {
|
|||
return err
|
||||
}
|
||||
|
||||
|
||||
func SendToMailTpl(title, user, password, host, to, tplname string, content interface{}, mailtype string, ifgenerate bool) error {
|
||||
var content_type string
|
||||
var paseresult bytes.Buffer
|
||||
|
@ -248,18 +248,18 @@ func OnSendEmailCode(c *gin.Context) {
|
|||
resp.Msg = "ParaErr"
|
||||
return
|
||||
}
|
||||
if req.Email != ""{
|
||||
if req.Email != "" {
|
||||
type Count struct {
|
||||
Count int32 `json:"count"`
|
||||
}
|
||||
cnt := []Count{}
|
||||
query := fmt.Sprintf("select count(*) as count from users where users.email_address = %s",req.Email)
|
||||
e := db.GetMysqlClient().Query2(query,&cnt)
|
||||
if nil !=e {
|
||||
query := fmt.Sprintf("select count(*) as count from users where users.email_address = %s", req.Email)
|
||||
e := db.GetMysqlClient().Query2(query, &cnt)
|
||||
if nil != e {
|
||||
log.Println(e.Error())
|
||||
return
|
||||
}
|
||||
}else {
|
||||
} else {
|
||||
return
|
||||
}
|
||||
user := "c7458969@163.com"
|
||||
|
@ -270,8 +270,8 @@ func OnSendEmailCode(c *gin.Context) {
|
|||
//发送
|
||||
verCode := controller.CreateVerify(6)
|
||||
content := "您的验证码是" + verCode
|
||||
userKey := fmt.Sprintf("user_%s_verify",req.Email)
|
||||
config.RedisOne().Set(userKey,verCode,time.Hour * 24)
|
||||
userKey := fmt.Sprintf("user_%s_verify", req.Email)
|
||||
config.RedisOne().Set(userKey, verCode, time.Hour*24)
|
||||
e = SendToMail("后台管理系统验证码", user, password, host, req.Email, content)
|
||||
if nil != e {
|
||||
log.Println(e.Error())
|
||||
|
@ -279,4 +279,4 @@ func OnSendEmailCode(c *gin.Context) {
|
|||
return
|
||||
}
|
||||
resp.Msg = "OK"
|
||||
}
|
||||
}
|
||||
|
|
81
db/db.go
81
db/db.go
|
@ -15,7 +15,7 @@ import (
|
|||
// 数据容器抽象对象定义
|
||||
type Database struct {
|
||||
Type string // 用来给SqlBuilder进行一些特殊的判断 (空值或mysql 皆表示这是一个MySQL实例)
|
||||
DB *sql.DB
|
||||
DB *sql.DB
|
||||
}
|
||||
|
||||
// SQL异步执行队列定义
|
||||
|
@ -231,14 +231,14 @@ func (this *Database) queryAndReflect(sql string,
|
|||
case reflect.Float32:
|
||||
if nil != row[i] {
|
||||
//log.Println(row[i].(float32))
|
||||
switch reflect.TypeOf(row[i]).Kind(){
|
||||
switch reflect.TypeOf(row[i]).Kind() {
|
||||
case reflect.Slice:
|
||||
v, e := strconv.ParseFloat(string(row[i].([]byte)), 0)
|
||||
if nil == e {
|
||||
feild.Field(n).SetFloat(float64(v))
|
||||
//feild.Field(n).SetFloat(float64(row[i].(float32)))
|
||||
}
|
||||
break
|
||||
break
|
||||
case reflect.Float64:
|
||||
feild.Field(n).SetFloat(float64(row[i].(float32)))
|
||||
}
|
||||
|
@ -312,59 +312,59 @@ func (this *Database) Delete(query string, args ...interface{}) (int64, error) {
|
|||
return this.Update(query, args...)
|
||||
}
|
||||
|
||||
func GenSql(obj interface{}) (string,error) {
|
||||
func GenSql(obj interface{}) (string, error) {
|
||||
ret := ""
|
||||
typ := reflect.TypeOf(obj).Kind()
|
||||
if typ != reflect.Struct{
|
||||
return (""),errors.New("not a struct")
|
||||
if typ != reflect.Struct {
|
||||
return (""), errors.New("not a struct")
|
||||
}
|
||||
value := obj.(reflect.Value)
|
||||
num := value.NumField()
|
||||
for i := 0;i < num;i++{
|
||||
if i == 0{
|
||||
for i := 0; i < num; i++ {
|
||||
if i == 0 {
|
||||
ret += "("
|
||||
}
|
||||
switch (value.Field(i).Type().Kind()){
|
||||
switch value.Field(i).Type().Kind() {
|
||||
case reflect.String:
|
||||
str := value.Field(i).Interface().(string)
|
||||
if str[0] != '"'{
|
||||
ret += "\""
|
||||
str := value.Field(i).Interface().(string)
|
||||
if str[0] != '"' {
|
||||
ret += "\""
|
||||
str += "\""
|
||||
ret += str
|
||||
ret += str
|
||||
|
||||
}else{
|
||||
ret += value.Field(i).Interface().(string)
|
||||
} else {
|
||||
ret += value.Field(i).Interface().(string)
|
||||
}
|
||||
case reflect.Int:
|
||||
ret += fmt.Sprintf("%d",value.Field(i).Interface().(int))
|
||||
ret += fmt.Sprintf("%d", value.Field(i).Interface().(int))
|
||||
case reflect.Int8:
|
||||
ret += fmt.Sprintf("%d",value.Field(i).Interface().(int8))
|
||||
ret += fmt.Sprintf("%d", value.Field(i).Interface().(int8))
|
||||
case reflect.Int32:
|
||||
ret += fmt.Sprintf("%d",value.Field(i).Interface().(int32))
|
||||
ret += fmt.Sprintf("%d", value.Field(i).Interface().(int32))
|
||||
case reflect.Int64:
|
||||
ret += fmt.Sprintf("%d",value.Field(i).Interface().(int64))
|
||||
ret += fmt.Sprintf("%d", value.Field(i).Interface().(int64))
|
||||
case reflect.Int16:
|
||||
ret += fmt.Sprintf("%d",value.Field(i).Interface().(int16))
|
||||
ret += fmt.Sprintf("%d", value.Field(i).Interface().(int16))
|
||||
case reflect.Bool:
|
||||
if value.Field(i).Interface().(bool) {
|
||||
ret += fmt.Sprintf("true",)
|
||||
}else {
|
||||
ret += fmt.Sprintf("false",)
|
||||
ret += fmt.Sprintf("true")
|
||||
} else {
|
||||
ret += fmt.Sprintf("false")
|
||||
}
|
||||
case reflect.Float32:
|
||||
ret += fmt.Sprintf("%x",value.Field(i).Interface().(float32))
|
||||
ret += fmt.Sprintf("%x", value.Field(i).Interface().(float32))
|
||||
case reflect.Float64:
|
||||
ret += fmt.Sprintf("true",value.Field(i).Interface().(float64))
|
||||
ret += fmt.Sprintf("true", value.Field(i).Interface().(float64))
|
||||
}
|
||||
if i == num - 1{
|
||||
if i == num-1 {
|
||||
ret += ")"
|
||||
}else {
|
||||
} else {
|
||||
ret += ","
|
||||
}
|
||||
}
|
||||
return ret,nil
|
||||
return ret, nil
|
||||
}
|
||||
func (this *Database) InsertObejct(tb_name string,obj interface{}) (int64,error) {
|
||||
func (this *Database) InsertObejct(tb_name string, obj interface{}) (int64, error) {
|
||||
var tagMap map[int]string
|
||||
var tp, tps reflect.Type
|
||||
var n, i int
|
||||
|
@ -372,11 +372,11 @@ func (this *Database) InsertObejct(tb_name string,obj interface{}) (int64,error)
|
|||
// 检测val参数是否为我们所想要的参数
|
||||
tp = reflect.TypeOf(obj)
|
||||
if reflect.Ptr != tp.Kind() {
|
||||
return 0,errors.New("is not pointer")
|
||||
return 0, errors.New("is not pointer")
|
||||
}
|
||||
|
||||
if reflect.Slice != tp.Elem().Kind() {
|
||||
return 0,errors.New("is not slice pointer")
|
||||
return 0, errors.New("is not slice pointer")
|
||||
}
|
||||
|
||||
tp = tp.Elem()
|
||||
|
@ -384,9 +384,9 @@ func (this *Database) InsertObejct(tb_name string,obj interface{}) (int64,error)
|
|||
value := reflect.ValueOf(obj).Elem()
|
||||
|
||||
if reflect.Struct != tps.Kind() {
|
||||
return 0,errors.New("is not struct slice pointer")
|
||||
return 0, errors.New("is not struct slice pointer")
|
||||
}
|
||||
for z := 0; z < value.Len();z ++ {
|
||||
for z := 0; z < value.Len(); z++ {
|
||||
tagMap = make(map[int]string)
|
||||
n = tps.NumField()
|
||||
var query_struct string
|
||||
|
@ -395,28 +395,29 @@ func (this *Database) InsertObejct(tb_name string,obj interface{}) (int64,error)
|
|||
if len(tag) > 0 {
|
||||
tagMap[i] = tag
|
||||
}
|
||||
if i == 0{
|
||||
if i == 0 {
|
||||
query_struct += "("
|
||||
}
|
||||
query_struct += tagMap[i]
|
||||
if i == n -1{
|
||||
if i == n-1 {
|
||||
query_struct += ")"
|
||||
}else {
|
||||
} else {
|
||||
query_struct += ","
|
||||
}
|
||||
}
|
||||
vs ,e := GenSql(value.Index(z))
|
||||
if nil != e{
|
||||
vs, e := GenSql(value.Index(z))
|
||||
if nil != e {
|
||||
logs.Error(e.Error())
|
||||
}
|
||||
query := "insert into " + tb_name + query_struct + "values " + vs
|
||||
_, e = this.Insert(query)
|
||||
if e != nil{
|
||||
if e != nil {
|
||||
logs.Error(e.Error())
|
||||
}
|
||||
}
|
||||
return 0,nil
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// 执行INSERT语句并返回最后生成的自增ID
|
||||
// 返回0表示没有出错, 但没生成自增ID
|
||||
// 返回-1表示出错
|
||||
|
|
14
db/mssql.go
14
db/mssql.go
|
@ -7,7 +7,7 @@ import (
|
|||
|
||||
// ProcExec 执行存储过程, 返回受影响的行数
|
||||
func (this *Database) ExecProc(procname string, params ...interface{}) (int64, error) {
|
||||
result, err := this.Exec("EXEC " + procname + " " + this.GetProcPlaceholder(len(params)), params...)
|
||||
result, err := this.Exec("EXEC "+procname+" "+this.GetProcPlaceholder(len(params)), params...)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
@ -33,20 +33,20 @@ func (this *Database) GetExecProcErr(procname string, params ...interface{}) err
|
|||
|
||||
// ProcQuery 通过存储过程查询记录
|
||||
func (this *Database) ProcQuery(procname string, params ...interface{}) (rows *sql.Rows, err error) {
|
||||
rows, err = this.Query("EXEC " + procname + " " + this.GetProcPlaceholder(len(params)), params...)
|
||||
rows, err = this.Query("EXEC "+procname+" "+this.GetProcPlaceholder(len(params)), params...)
|
||||
return
|
||||
}
|
||||
|
||||
// ProcQueryRow 通过存储过程查询单条记录
|
||||
func (this *Database) ProcQueryRow(procname string, params ...interface{}) *sql.Row {
|
||||
return this.QueryRow("EXEC " + procname + " " + this.GetProcPlaceholder(len(params)), params...)
|
||||
return this.QueryRow("EXEC "+procname+" "+this.GetProcPlaceholder(len(params)), params...)
|
||||
}
|
||||
|
||||
// ProcStatus 调用存储过程并获取最终的执行状态码和提示信息
|
||||
func (this *Database) ProcStatus(procname string, params ...interface{}) (int, string) {
|
||||
var status int
|
||||
var msg string
|
||||
err := this.QueryRow("EXEC " + procname + " " + this.GetProcPlaceholder(len(params)), params...).Scan(&status, &msg)
|
||||
err := this.QueryRow("EXEC "+procname+" "+this.GetProcPlaceholder(len(params)), params...).Scan(&status, &msg)
|
||||
if err != nil {
|
||||
return -99, err.Error()
|
||||
}
|
||||
|
@ -55,12 +55,12 @@ func (this *Database) ProcStatus(procname string, params ...interface{}) (int, s
|
|||
|
||||
// ProcSelect 通过存储过程查询结果集
|
||||
func (this *Database) ProcSelect(procname string, params ...interface{}) (Results, error) {
|
||||
return this.Select("EXEC " + procname + " " + this.GetProcPlaceholder(len(params)), params...)
|
||||
return this.Select("EXEC "+procname+" "+this.GetProcPlaceholder(len(params)), params...)
|
||||
}
|
||||
|
||||
// ProcSelectOne 通过存储查询一行不定字段的结果
|
||||
func (this *Database) ProcSelectOne(procname string, params ...interface{}) (OneRow, error) {
|
||||
return this.SelectOne("EXEC " + procname + " " + this.GetProcPlaceholder(len(params)), params...)
|
||||
return this.SelectOne("EXEC "+procname+" "+this.GetProcPlaceholder(len(params)), params...)
|
||||
}
|
||||
|
||||
// GetProcPlaceholder 按照指定数量生成调用存储过程时所用的参数占位符
|
||||
|
@ -73,4 +73,4 @@ func (this *Database) GetProcPlaceholder(count int) (placeholder string) {
|
|||
placeholder += "?"
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
|
|
@ -9,23 +9,21 @@ import (
|
|||
|
||||
var gDb Database
|
||||
|
||||
func Init() {
|
||||
func Init() {
|
||||
mysqlconf := config.GetMysqlConfig()
|
||||
cnn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8",mysqlconf.UserName,mysqlconf.Password,
|
||||
mysqlconf.Addr,mysqlconf.Db)
|
||||
_db,err := sql.Open("mysql",cnn)
|
||||
if err != nil{
|
||||
fmt.Println("connect sql server ",err.Error())
|
||||
cnn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8", mysqlconf.UserName, mysqlconf.Password,
|
||||
mysqlconf.Addr, mysqlconf.Db)
|
||||
_db, err := sql.Open("mysql", cnn)
|
||||
if err != nil {
|
||||
fmt.Println("connect sql server ", err.Error())
|
||||
}
|
||||
e := _db.Ping()
|
||||
if nil != e{
|
||||
if nil != e {
|
||||
fmt.Println(e.Error())
|
||||
}
|
||||
gDb = Database{Type:string(""),DB:_db}
|
||||
gDb = Database{Type: string(""), DB: _db}
|
||||
}
|
||||
|
||||
func GetMysqlClient() *Database {
|
||||
return &gDb
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -3,18 +3,18 @@ package db
|
|||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"math/big"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"log"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"math/big"
|
||||
|
||||
"git.jiaxianghudong.com/go/utils"
|
||||
)
|
||||
|
||||
const (
|
||||
_ = iota
|
||||
_ = iota
|
||||
TYPE_INSERT
|
||||
TYPE_DELETE
|
||||
TYPE_UPDATE
|
||||
|
@ -24,31 +24,31 @@ const (
|
|||
|
||||
var (
|
||||
WrapSymbol = "`"
|
||||
DBType = "mysql"
|
||||
DBType = "mysql"
|
||||
)
|
||||
|
||||
// SQL语句构造结构
|
||||
type SB struct {
|
||||
db *Database
|
||||
t int
|
||||
db *Database
|
||||
t int
|
||||
field, table, where, group, order, limit string
|
||||
values SBValues
|
||||
values2 SBValues
|
||||
ignore bool
|
||||
fullsql bool
|
||||
debug bool
|
||||
unsafe bool //是否进行安全检查, 专门针对无限定的UPDATE和DELETE进行二次验证
|
||||
args []interface{}
|
||||
values SBValues
|
||||
values2 SBValues
|
||||
ignore bool
|
||||
fullsql bool
|
||||
debug bool
|
||||
unsafe bool //是否进行安全检查, 专门针对无限定的UPDATE和DELETE进行二次验证
|
||||
args []interface{}
|
||||
}
|
||||
|
||||
// Exec返回结果
|
||||
type SBResult struct {
|
||||
Success bool //语句是否执行成功
|
||||
Code int //错误代码
|
||||
Msg string //错误提示信息
|
||||
LastID int64 //最后产生的ID
|
||||
Affected int64 //受影响的行数
|
||||
Sql string //最后执行的SQL
|
||||
Success bool //语句是否执行成功
|
||||
Code int //错误代码
|
||||
Msg string //错误提示信息
|
||||
LastID int64 //最后产生的ID
|
||||
Affected int64 //受影响的行数
|
||||
Sql string //最后执行的SQL
|
||||
}
|
||||
|
||||
// 值对象
|
||||
|
@ -56,7 +56,7 @@ type SBValues map[string]interface{}
|
|||
|
||||
// 增量值
|
||||
type IncVal struct {
|
||||
Val int64
|
||||
Val int64
|
||||
BaseField string // 为空表示对当前字段累加
|
||||
}
|
||||
|
||||
|
@ -473,8 +473,8 @@ func (q *SB) Exec(args ...interface{}) *SBResult {
|
|||
case TYPE_INSERT:
|
||||
if DBType == "mysql" {
|
||||
last, err := ret.LastInsertId()
|
||||
if (err == nil) {
|
||||
sbRet.LastID = last;
|
||||
if err == nil {
|
||||
sbRet.LastID = last
|
||||
}
|
||||
}
|
||||
case TYPE_DELETE:
|
||||
|
@ -483,7 +483,7 @@ func (q *SB) Exec(args ...interface{}) *SBResult {
|
|||
fallthrough
|
||||
case TYPE_INSERTUPDATE:
|
||||
aff, err := ret.RowsAffected()
|
||||
if (err == nil) {
|
||||
if err == nil {
|
||||
sbRet.Affected = aff
|
||||
}
|
||||
}
|
||||
|
@ -539,4 +539,4 @@ func (q *SB) QueryRow(args ...interface{}) *sql.Row {
|
|||
log.Println("\n\tSQL prepare statement:\n\t", s, "\n\tParams:\n\t", args)
|
||||
}
|
||||
return q.db.QueryRow(s, args...)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"strconv"
|
||||
"database/sql"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// 根据传入的字段列表生成相符数量的占位符
|
||||
|
@ -53,7 +53,7 @@ func NewNullString(s string) sql.NullString {
|
|||
}
|
||||
return sql.NullString{
|
||||
String: s,
|
||||
Valid: true,
|
||||
Valid: true,
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -63,4 +63,4 @@ func NewNullInt64(s int64, isNull bool) sql.NullInt64 {
|
|||
Int64: s,
|
||||
Valid: !isNull,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -37,7 +37,7 @@ func Error(err ...interface{}) {
|
|||
func Waring(war ...interface{}) {
|
||||
log.write(LOG_WARING, fmt.Sprint(war...))
|
||||
}
|
||||
func SetLevel(level int) {
|
||||
func SetLevel(level int) {
|
||||
log.setLevel(level)
|
||||
}
|
||||
func Info(info ...interface{}) {
|
||||
|
|
50
main.go
50
main.go
|
@ -5,48 +5,47 @@ import (
|
|||
"github.com/tommy351/gin-sessions"
|
||||
"log"
|
||||
"strconv"
|
||||
"user/controller"
|
||||
"user/config"
|
||||
"user/controller"
|
||||
"user/controller/mail"
|
||||
"user/db"
|
||||
"user/logs"
|
||||
)
|
||||
|
||||
func InitMysql() {
|
||||
func InitMysql() {
|
||||
c := config.GetMysqlConfig()
|
||||
if c == nil{
|
||||
if c == nil {
|
||||
logs.Error("cannnot connect mysql server")
|
||||
}else {
|
||||
} else {
|
||||
db.Init()
|
||||
}
|
||||
}
|
||||
func CORSMiddleware(c *gin.Context) {
|
||||
ori := c.Request.Header.Get("Origin")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin",ori)
|
||||
log.Println(c.Request.Header.Get("Origin"))
|
||||
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, x-access-token")
|
||||
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
ori := c.Request.Header.Get("Origin")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", ori)
|
||||
c.Writer.Header().Set("Access-Control-Max-Age", "86400")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, x-access-token")
|
||||
c.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
log.Println("OPTIONS")
|
||||
c.AbortWithStatus(200)
|
||||
} else {
|
||||
c.Next()
|
||||
}
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
log.Println("OPTIONS")
|
||||
c.AbortWithStatus(200)
|
||||
} else {
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
func main() {
|
||||
e := config.Init("user.yaml")
|
||||
if nil != e{
|
||||
if nil != e {
|
||||
log.Println(e.Error())
|
||||
}
|
||||
logs.Init(config.GetLogConfig().Dir,config.GetLogConfig().File,config.GetLogConfig().Level,config.GetLogConfig().SaveFile)
|
||||
logs.Init(config.GetLogConfig().Dir, config.GetLogConfig().File, config.GetLogConfig().Level, config.GetLogConfig().SaveFile)
|
||||
db.Init()
|
||||
e = config.InitRedis()
|
||||
if nil != e{
|
||||
if nil != e {
|
||||
logs.Error(e.Error())
|
||||
return
|
||||
}
|
||||
|
@ -70,7 +69,10 @@ func main() {
|
|||
r.POST("/api/register", controller.Register)
|
||||
/** 用户退出登陆 **/
|
||||
r.GET("/api/logout", controller.Logout)
|
||||
r.POST("/api/verify",mail.OnSendEmailCode)
|
||||
r.POST("/api/verify", mail.OnSendEmailCode)
|
||||
}
|
||||
e = r.Run(":" + strconv.Itoa(config.GetPort()))
|
||||
if nil != e{
|
||||
log.Print(e.Error())
|
||||
}
|
||||
r.Run(":" + strconv.Itoa(config.GetPort()))
|
||||
}
|
||||
|
|
|
@ -2,35 +2,35 @@ package model
|
|||
|
||||
import (
|
||||
"fmt"
|
||||
"qiniupkg.com/x/log.v7"
|
||||
"log"
|
||||
"user/db"
|
||||
"user/logs"
|
||||
)
|
||||
|
||||
type Users struct {
|
||||
ID int64 `sql:"id" json:"id"`
|
||||
UserName string `sql:"user_name" json:"user_name"`
|
||||
UserPwd string `sql:"user_pwd" json:"-"`
|
||||
CreatedDate string `sql:"created_date" json:"created_date"`
|
||||
UpdatedDate string `sql:"updated_date" json:"updated_date"`
|
||||
DisplayName string `sql:"display_name" json:"display_name"`
|
||||
ID int64 `sql:"id" json:"id"`
|
||||
UserName string `sql:"user_name" json:"user_name"`
|
||||
UserPwd string `sql:"user_pwd" json:"-"`
|
||||
CreatedDate string `sql:"created_date" json:"created_date"`
|
||||
UpdatedDate string `sql:"updated_date" json:"updated_date"`
|
||||
DisplayName string `sql:"display_name" json:"display_name"`
|
||||
EmailAddress string `sql:"email_address" json:"email_address"`
|
||||
Tel string `sql:"tel" json:"tel"`
|
||||
Avatar string `sql:"avatar" json:"avatar"`
|
||||
Tel string `sql:"tel" json:"tel"`
|
||||
Avatar string `sql:"avatar" json:"avatar"`
|
||||
}
|
||||
|
||||
func GetUsers(limit int32,offsetPage int32,name string) ([]Users,int32){
|
||||
func GetUsers(limit int32, offsetPage int32, name string) ([]Users, int32) {
|
||||
users := []Users{}
|
||||
var query string
|
||||
if name != ""{
|
||||
if name != "" {
|
||||
log.Println(name)
|
||||
query = fmt.Sprintf("select * from users where user_name like '%s' limit %d offset %d","%%" + name + "%%",limit,offsetPage*limit)
|
||||
query = fmt.Sprintf("select * from users where user_name like '%s' limit %d offset %d", "%%"+name+"%%", limit, offsetPage*limit)
|
||||
log.Printf(query)
|
||||
}else {
|
||||
query = fmt.Sprintf("select * from users limit %d offset %d",limit,offsetPage*limit)
|
||||
} else {
|
||||
query = fmt.Sprintf("select * from users limit %d offset %d", limit, offsetPage*limit)
|
||||
}
|
||||
err := db.GetMysqlClient().Query2(query,&users)
|
||||
if nil != err{
|
||||
err := db.GetMysqlClient().Query2(query, &users)
|
||||
if nil != err {
|
||||
logs.Error(err.Error())
|
||||
}
|
||||
type Count struct {
|
||||
|
@ -38,11 +38,9 @@ func GetUsers(limit int32,offsetPage int32,name string) ([]Users,int32){
|
|||
}
|
||||
cnts := []Count{}
|
||||
query = fmt.Sprintf("select count(*) as count from users")
|
||||
err = db.GetMysqlClient().Query2(query,&cnts)
|
||||
if nil != err{
|
||||
err = db.GetMysqlClient().Query2(query, &cnts)
|
||||
if nil != err {
|
||||
logs.Error(err.Error())
|
||||
}
|
||||
return users,cnts[0].Count
|
||||
return users, cnts[0].Count
|
||||
}
|
||||
|
||||
|
||||
|
|
Loading…
Reference in New Issue