├── README.md ├── conf ├── app_example.conf ├── dev │ └── database_example.conf └── prod │ └── database_example.conf ├── controllers ├── base.go ├── object.go └── user │ └── user.go ├── libs ├── define │ ├── ret.go │ └── user.go └── proto │ └── user.go ├── logic └── userLogic │ └── user.go ├── main.go ├── models ├── init.go ├── object.go └── userModel │ └── user.go ├── module ├── config │ └── config.go ├── redis │ └── redis.go └── util │ └── util.go ├── routers └── router.go └── tests └── default_test.go /README.md: -------------------------------------------------------------------------------- 1 | ### 简介 2 | 1. im_api 是im中需要的一些简单接口,基于[beego框架 ](https://beego.me/docs/intro/) 3 | 4 | 5 | ### 部署 6 | mysql执行,创建用户表 7 | ``` 8 | CREATE TABLE `tb_user` ( 9 | `id` varchar(32) NOT NULL, 10 | `user_name` varchar(16) NOT NULL, 11 | `password` varchar(32) NOT NULL, 12 | `create_time` int(10) NOT NULL, 13 | `update_time` int(10) NOT NULL, 14 | PRIMARY KEY (`id`) 15 | ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT; 16 | ``` 17 | 部署项目 18 | ``` 19 | cd $GOPATH/src/ 20 | go get github.com/beego/bee 21 | git clone https://github.com/Terry-Ye/im_api.git 22 | cd im_api 23 | mv conf/dev/database_example.conf conf/dev/database.conf // 根据自身情况修改配置 24 | 25 | $GOPATH/bin/bee run 26 | ``` 27 | 28 | 29 | 30 | 31 | ### 部署注意事项 32 | 1. 部署服务器注意防火墙是否开放对应的端口(本地不需要,具体需要的端口在各层的配置文件) 33 | 34 | 35 | ### api 文档 36 | 37 | #### 注册接口 38 | 39 | * http 请求方式:post 40 | * 请求地址:http://localhost:8080/v1/user/register 41 | * 请求参数 42 | ``` 43 | { 44 | "UserName":"terry4444", 45 | "Password":"terry4444" 46 | } 47 | ``` 48 | * 返回数据格式(示例) 49 | ``` 50 | { 51 | "code":0, 52 | "msg":"success" 53 | } 54 | ``` 55 | 56 | 57 | #### 登录接口 58 | 59 | * http 请求方式:post 60 | * 请求地址:http://localhost:8080/v1/user/login 61 | * 请求参数 62 | ``` 63 | { 64 | "UserName":"terry4444", 65 | "Password":"terry4444" 66 | } 67 | ``` 68 | * 返回数据格式(示例) 69 | ``` 70 | { 71 | "code":0, 72 | "msg":"success" 73 | } 74 | ``` 75 | 76 | #### 检查auth接口 77 | 78 | * http 请求方式:get 79 | * 请求地址:http://localhost:8080/v1/user/login 80 | * 请求参数 81 | ``` 82 | { 83 | "Auth":"8e11412585c38a7d" 84 | } 85 | ``` 86 | * 返回数据格式(示例) 87 | ``` 88 | { 89 | "code": 0, 90 | "msg": "请求成功", 91 | "data": { 92 | "Auth": "5fee48a98f1c78f5", 93 | "UserId": "863440c38d717354", 94 | "UserName": "terry4444" 95 | } 96 | } 97 | ``` 98 | 99 | #### 更新在线人数(由ws推送) 100 | 101 | * http 请求方式:get 102 | * 请求地址:http://localhost:6921/api/v1/count?rid=1 103 | * 返回数据格式(示例) 104 | ``` 105 | { 106 | "code":0, 107 | "msg":"success" 108 | } 109 | ``` -------------------------------------------------------------------------------- /conf/app_example.conf: -------------------------------------------------------------------------------- 1 | appname = web 2 | httpport = 8081 3 | runmode = dev 4 | autorender = false 5 | copyrequestbody = true 6 | EnableDocs = true 7 | 8 | EnableHTTPS = true 9 | EnableHttpTLS = true 10 | HttpsPort = 8080 11 | HTTPSCertFile = "" 12 | HTTPSKeyFile = "" 13 | -------------------------------------------------------------------------------- /conf/dev/database_example.conf: -------------------------------------------------------------------------------- 1 | [mysql] 2 | host = localhost 3 | port = 8889 4 | username = www 5 | password = 123456 6 | 7 | [redis] 8 | RedisAddr = 127.0.0.1:6379 9 | RedisPw = 10 | RedisDefaultDB = 0 11 | RedisPrefix = im_ -------------------------------------------------------------------------------- /conf/prod/database_example.conf: -------------------------------------------------------------------------------- 1 | [mysql] 2 | host = localhost 3 | port = 8889 4 | username = www 5 | password = 123456 6 | 7 | [redis] 8 | RedisAddr = 127.0.0.1:6379 9 | RedisPw = 10 | RedisDefaultDB = 0 11 | RedisPrefix = im_ -------------------------------------------------------------------------------- /controllers/base.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "github.com/astaxie/beego" 5 | "github.com/astaxie/beego/validation" 6 | "im_api/libs/define" 7 | ) 8 | 9 | type DataNil struct { 10 | } 11 | 12 | // Operations about Users 13 | type BaseController struct { 14 | beego.Controller 15 | } 16 | 17 | type RetData struct { 18 | Code int `json:"code"` 19 | Msg string `json:"msg"` 20 | Data interface{} `json:"data"` 21 | } 22 | 23 | 24 | 25 | func (c *BaseController) RenderData(code int, msg string, data interface{}) (retData RetData) { 26 | retData.Code = code 27 | retData.Msg = msg 28 | retData.Data = data 29 | return retData 30 | } 31 | 32 | func (c *BaseController) RenderDataSimple(code int, msg string) (retData RetData){ 33 | beego.Debug("code %v", code) 34 | retData.Code = code 35 | retData.Msg = msg 36 | retData.Data = DataNil{} 37 | return 38 | 39 | } 40 | 41 | func (c *BaseController) CheckParams(dataModel interface{}) (code int, msg string){ 42 | // beego.Error("dataModel Valid err : %v", dataModel) 43 | valid := validation.Validation{} 44 | b, err := valid.Valid(dataModel) 45 | if err != nil { 46 | code = define.ERR_SYSTEM_EXCEPTION_CODE 47 | msg = define.ERR_SYSTEM_EXCEPTION_MSG 48 | beego.Error("Register Valid err : %v", err) 49 | return 50 | } 51 | if !b { 52 | for _, err := range valid.Errors { 53 | code = define.ERR_PARAM_VAILD_CODE 54 | msg = err.Key+ ":" + err.Message 55 | return 56 | } 57 | } 58 | return 59 | } 60 | 61 | -------------------------------------------------------------------------------- /controllers/object.go: -------------------------------------------------------------------------------- 1 | package controllers 2 | 3 | import ( 4 | "im_api/models" 5 | "encoding/json" 6 | 7 | "github.com/astaxie/beego" 8 | ) 9 | 10 | // Operations about object 11 | type ObjectController struct { 12 | beego.Controller 13 | } 14 | 15 | // @Title Create 16 | // @Description create object 17 | // @Param body body models.Object true "The object content" 18 | // @Success 200 {string} models.Object.Id 19 | // @Failure 403 body is empty 20 | // @router / [post] 21 | func (o *ObjectController) Post() { 22 | var ob models.Object 23 | json.Unmarshal(o.Ctx.Input.RequestBody, &ob) 24 | objectid := models.AddOne(ob) 25 | o.Data["json"] = map[string]string{"ObjectId": objectid} 26 | o.ServeJSON() 27 | } 28 | 29 | // @Title Get 30 | // @Description find object by objectid 31 | // @Param objectId path string true "the objectid you want to get" 32 | // @Success 200 {object} models.Object 33 | // @Failure 403 :objectId is empty 34 | // @router /:objectId [get] 35 | func (o *ObjectController) Get() { 36 | objectId := o.Ctx.Input.Param(":objectId") 37 | if objectId != "" { 38 | ob, err := models.GetOne(objectId) 39 | if err != nil { 40 | o.Data["json"] = err.Error() 41 | } else { 42 | o.Data["json"] = ob 43 | } 44 | } 45 | o.ServeJSON() 46 | } 47 | 48 | // @Title GetAll 49 | // @Description get all objects 50 | // @Success 200 {object} models.Object 51 | // @Failure 403 :objectId is empty 52 | // @router / [get] 53 | func (o *ObjectController) GetAll() { 54 | obs := models.GetAll() 55 | o.Data["json"] = obs 56 | o.ServeJSON() 57 | } 58 | 59 | // @Title Update 60 | // @Description update the object 61 | // @Param objectId path string true "The objectid you want to update" 62 | // @Param body body models.Object true "The body" 63 | // @Success 200 {object} models.Object 64 | // @Failure 403 :objectId is empty 65 | // @router /:objectId [put] 66 | func (o *ObjectController) Put() { 67 | objectId := o.Ctx.Input.Param(":objectId") 68 | var ob models.Object 69 | json.Unmarshal(o.Ctx.Input.RequestBody, &ob) 70 | 71 | err := models.Update(objectId, ob.Score) 72 | if err != nil { 73 | o.Data["json"] = err.Error() 74 | } else { 75 | o.Data["json"] = "update success!" 76 | } 77 | o.ServeJSON() 78 | } 79 | 80 | // @Title Delete 81 | // @Description delete the object 82 | // @Param objectId path string true "The objectId you want to delete" 83 | // @Success 200 {string} delete success! 84 | // @Failure 403 objectId is empty 85 | // @router /:objectId [delete] 86 | func (o *ObjectController) Delete() { 87 | objectId := o.Ctx.Input.Param(":objectId") 88 | models.Delete(objectId) 89 | o.Data["json"] = "delete success!" 90 | o.ServeJSON() 91 | } 92 | 93 | -------------------------------------------------------------------------------- /controllers/user/user.go: -------------------------------------------------------------------------------- 1 | package user 2 | 3 | import ( 4 | "im_api/models/userModel" 5 | "im_api/controllers" 6 | "encoding/json" 7 | "im_api/logic/userLogic" 8 | "im_api/libs/define" 9 | ) 10 | 11 | // Operations about Users 12 | type UserController struct { 13 | controllers.BaseController 14 | } 15 | 16 | // type User struct { 17 | // Id string 18 | // Username string `valid:"Required;MinSize(3);MaxSize(32)"` 19 | // Password int `valid:"Required;MinSize(6);MaxSize(20)"` 20 | // CreateTime int64 21 | // } 22 | 23 | // @Title Login 24 | // @Description Logs user into the system 25 | // @Param username formData string true "The username for login" 26 | // @Param password formData string true "The password for login" 27 | // @Success 200 {string} login success 28 | // @Failure 403 user not exist 29 | // @router /login [post] 30 | func (u *UserController) Login() { 31 | var ( 32 | user userModel.User 33 | retData userLogic.ReturnInfo 34 | ) 35 | json.Unmarshal(u.Ctx.Input.RequestBody, &user) 36 | // userInfo := userModel.GetUserInfoByUserName(user.UserName) 37 | code, msg := u.CheckParams(user) 38 | if code != 0 { 39 | u.Data["json"] = u.RenderDataSimple(code, msg) 40 | u.ServeJSON() 41 | return 42 | } 43 | code, msg, retData = userLogic.Login(user) 44 | 45 | if code != 0 { 46 | u.Data["json"] = u.RenderDataSimple(code, msg) 47 | u.ServeJSON() 48 | return 49 | } 50 | 51 | u.Ctx.SetCookie("auth", retData.Auth, 86400, "/", "localhost", "", false) // 设置cookie 52 | 53 | u.Data["json"] = u.RenderData(code, msg, retData) 54 | u.ServeJSON() 55 | } 56 | 57 | // @Title Register 58 | // @Description Register user 59 | // @Param username formData string true "The username for register" 60 | // @Param password formData string true "The password for register" 61 | // @Success 200 {string} register success 62 | // @Failure 403 user not exist 63 | // @router /register [post] 64 | func (u *UserController) Register() { 65 | var ( 66 | user userModel.User 67 | ) 68 | json.Unmarshal(u.Ctx.Input.RequestBody, &user) 69 | 70 | code, msg := u.CheckParams(user) 71 | 72 | if code != 0 { 73 | u.Data["json"] = u.RenderDataSimple(code, msg) 74 | u.ServeJSON() 75 | return 76 | } 77 | code, msg = userLogic.CheckUserName(user.UserName) 78 | if code != 0 { 79 | u.Data["json"] = u.RenderDataSimple(code, msg) 80 | u.ServeJSON() 81 | return 82 | } 83 | code, msg = userLogic.AddOne(user) 84 | u.Data["json"] = u.RenderDataSimple(code, msg) 85 | u.ServeJSON() 86 | } 87 | 88 | // @Title CheckAuth 89 | // @Description Check Auth 90 | // @Param Auth formData string true "The Auth for CheckAuth" 91 | // @Success 200 {string} CheckAuth success 92 | // @Failure 403 user not exist 93 | // @router /check_auth [post] 94 | func (u *UserController) CheckAuth() { 95 | var ( 96 | authInfo userModel.Auth 97 | ) 98 | json.Unmarshal(u.Ctx.Input.RequestBody, &authInfo) 99 | 100 | code, msg := u.CheckParams(authInfo) 101 | if code != 0 { 102 | u.Data["json"] = u.RenderDataSimple(code, msg) 103 | u.ServeJSON() 104 | return 105 | } 106 | 107 | code, msg, retData := userLogic.CheckAuth(authInfo.Auth) 108 | u.Data["json"] = u.RenderData(code, msg, retData) 109 | 110 | 111 | u.ServeJSON() 112 | return 113 | 114 | } 115 | 116 | // @Title logout 117 | // @Description Logs out current logged in user session 118 | // @Success 200 {string} logout success 119 | // @router /logout [get] 120 | func (u *UserController) Logout() { 121 | auth := u.Input().Get("auth") 122 | if auth == "" { 123 | u.Data["json"] = u.RenderDataSimple(define.ERR_PARAM_VAILD_CODE, define.ERR_PARAM_VAILD_MSG) 124 | u.ServeJSON() 125 | return 126 | } 127 | 128 | code, msg := userLogic.DeleteAuth(auth) 129 | u.Data["json"] = u.RenderDataSimple(code, msg) 130 | 131 | u.ServeJSON() 132 | return 133 | 134 | 135 | } 136 | -------------------------------------------------------------------------------- /libs/define/ret.go: -------------------------------------------------------------------------------- 1 | package define 2 | 3 | const( 4 | SUCCESS_CODE = 0 5 | SUCCESS_MSG = "请求成功" 6 | // System exception 7 | ERR_SYSTEM_EXCEPTION_CODE = -11 8 | ERR_SYSTEM_EXCEPTION_MSG = "系统异常" 9 | 10 | ERR_PARAM_VAILD_CODE = -1 11 | ERR_PARAM_VAILD_MSG = "参数验证出错" 12 | 13 | // mysql exception 14 | ERR_MYSQL_EXCEPTION_CODE = -12 15 | ERR_MYSQL_EXCEPTION_MSG = "数据库操作异常" 16 | 17 | // -1001 -1100 用户相关 18 | ERR_USER_EXIST_CODE = -1001 19 | ERR_USER_EXIST_MSG = "用户名已存在" 20 | ERR_USER_PASSWORD_CODE = -1002 21 | ERR_USER_PASSWORD_MSG = "用户名密码有误" 22 | ERR_USER_NO_EXIST_CODE = -1003 23 | ERR_USER_NO_EXIST_MSG = "用户不存在" 24 | 25 | ERR_USER_AUTH_INVALID_CODE = -1004 26 | ERR_USER_AUTH_INVALID_MSG = "用户AUTH失效" 27 | 28 | 29 | 30 | 31 | ) -------------------------------------------------------------------------------- /libs/define/user.go: -------------------------------------------------------------------------------- 1 | package define 2 | 3 | const( 4 | 5 | ) -------------------------------------------------------------------------------- /libs/proto/user.go: -------------------------------------------------------------------------------- 1 | package proto 2 | 3 | type AuthInfo struct { 4 | UserId string `json:"id"` 5 | UserName string `json:"UserName"` 6 | ServerId string `json:"ServerId"` 7 | } 8 | -------------------------------------------------------------------------------- /logic/userLogic/user.go: -------------------------------------------------------------------------------- 1 | package userLogic 2 | 3 | import ( 4 | "im_api/models/userModel" 5 | "im_api/libs/define" 6 | "im_api/module/util" 7 | "im_api/module/redis" 8 | "github.com/astaxie/beego" 9 | "github.com/smallnest/rpcx/log" 10 | ) 11 | 12 | const REDIS_PREFIX = "im_" 13 | type ReturnInfo struct { 14 | Auth string 15 | UserId string 16 | UserName string 17 | } 18 | 19 | func CheckUserName(userName string) (code int, msg string) { 20 | status := userModel.CheckoutUserNameExist(userName) 21 | if status == false { 22 | code = define.ERR_USER_EXIST_CODE 23 | msg = define.ERR_USER_EXIST_MSG 24 | } 25 | code = define.SUCCESS_CODE 26 | msg = define.SUCCESS_MSG 27 | return 28 | } 29 | 30 | func CheckAuth(auth string) (code int, msg string, ret ReturnInfo) { 31 | // var user userModel.User 32 | 33 | err := redis.InitRedis() 34 | if err != nil { 35 | beego.Error("redis init err: %s", err) 36 | } 37 | 38 | userInfo, err := redis.HGetAll(auth) 39 | log.Debug("userinfo %v", userInfo) 40 | if err != nil { 41 | beego.Debug("json err %s", err) 42 | code = define.ERR_USER_NO_EXIST_CODE 43 | msg = define.ERR_USER_NO_EXIST_MSG 44 | return 45 | } 46 | 47 | if _, ok := userInfo["UserName"]; !ok { 48 | code = define.ERR_USER_AUTH_INVALID_CODE 49 | msg = define.ERR_USER_AUTH_INVALID_MSG 50 | return 51 | } 52 | 53 | ret.UserName = userInfo["UserName"] 54 | ret.UserId = userInfo["UserId"] 55 | ret.Auth = auth 56 | 57 | code = define.SUCCESS_CODE 58 | msg = define.SUCCESS_MSG 59 | return 60 | 61 | } 62 | 63 | func AddOne(user userModel.User) (code int, msg string) { 64 | user.Id = util.GenUuid() 65 | user.Password = util.Md5(user.Password) 66 | code, msg = userModel.AddOne(user) 67 | return 68 | 69 | } 70 | 71 | func Login(user userModel.User) (code int, msg string, RetData ReturnInfo) { 72 | userInfo := userModel.GetUserInfoByUserName(user.UserName) 73 | // password err 74 | if util.Md5(user.Password) != userInfo.Password { 75 | beego.Debug("lgin password %s, userinfo %s,", user.Password, userInfo.Password) 76 | code = define.ERR_USER_PASSWORD_CODE 77 | msg = define.ERR_USER_PASSWORD_MSG 78 | return 79 | } 80 | err := redis.InitRedis() 81 | if err != nil { 82 | beego.Error("redis init err: %s", err) 83 | } 84 | auth := util.GenUuid() 85 | beego.Debug("user info %v", userInfo) 86 | userData := make(map[string]interface{}, 2) 87 | userData["UserId"] = userInfo.Id 88 | userData["UserName"] = userInfo.UserName 89 | 90 | err = redis.HMSet(auth, userData) 91 | 92 | RetData = ReturnInfo{auth, userInfo.Id, userInfo.UserName} 93 | if err != nil { 94 | beego.Error("redis set auth err: %s", err) 95 | } 96 | 97 | 98 | code = define.SUCCESS_CODE 99 | msg = define.SUCCESS_MSG 100 | return 101 | } 102 | 103 | func DeleteAuth(auth string) (code int, msg string) { 104 | err := redis.InitRedis() 105 | if err != nil { 106 | beego.Error("redis init err: %s", err) 107 | } 108 | 109 | if err := redis.Delete(auth); err != nil { 110 | beego.Error("redis delete auth err: %s", err) 111 | } 112 | 113 | code = define.SUCCESS_CODE 114 | msg = define.SUCCESS_MSG 115 | return 116 | } 117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | _ "im_api/routers" 5 | 6 | "github.com/astaxie/beego" 7 | "github.com/astaxie/beego/plugins/cors" 8 | ) 9 | 10 | func main() { 11 | if beego.BConfig.RunMode == "dev" { 12 | beego.BConfig.WebConfig.DirectoryIndex = true 13 | beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger" 14 | } 15 | 16 | beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{ 17 | AllowAllOrigins: true, 18 | AllowMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"}, 19 | AllowHeaders: []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"}, 20 | ExposeHeaders: []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"}, 21 | AllowCredentials: true, 22 | })) 23 | 24 | 25 | beego.Run() 26 | } 27 | -------------------------------------------------------------------------------- /models/init.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "github.com/astaxie/beego/orm" 5 | "im_api/module/config" 6 | 7 | "github.com/astaxie/beego" 8 | "strings" 9 | "im_api/models/userModel" 10 | _ "github.com/go-sql-driver/mysql" 11 | ) 12 | 13 | var confDbStr string 14 | 15 | func init() { 16 | 17 | orm.RegisterDriver("mysql", orm.DRMySQL) 18 | config, err := config.Reader("database.conf") 19 | if err != nil { 20 | beego.Error("config reader err: %v", err) 21 | } 22 | 23 | host := config.String("mysql::host") 24 | 25 | port := config.String("mysql::port") 26 | userStr := config.String("mysql::username") 27 | password := config.String("mysql::password") 28 | 29 | confDbStr = userStr+":"+ password +"@(" + host + ":" + port + ")/{{DB_NAME}}?charset=utf8" 30 | 31 | 32 | orm.RegisterDataBase("default", "mysql", getDbStr(userModel.USER_DB), 30) 33 | orm.RegisterModelWithPrefix("tb_", new(userModel.User)) 34 | orm.SetMaxIdleConns("default", 1000) 35 | orm.SetMaxOpenConns("default", 1000) 36 | 37 | // db,_ := orm.GetDB("mysql") 38 | // db.SetConnMaxLifetime(3) 39 | // orm.RegisterModel(new(UserModel.User)) 40 | 41 | } 42 | 43 | 44 | 45 | func getDbStr(dbname string) string { 46 | return strings.Replace(confDbStr, "{{DB_NAME}}", dbname, -1) 47 | } -------------------------------------------------------------------------------- /models/object.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | import ( 4 | "errors" 5 | "strconv" 6 | "time" 7 | ) 8 | 9 | var ( 10 | Objects map[string]*Object 11 | ) 12 | 13 | type Object struct { 14 | ObjectId string 15 | Score int64 16 | PlayerName string 17 | } 18 | 19 | func init() { 20 | Objects = make(map[string]*Object) 21 | Objects["hjkhsbnmn123"] = &Object{"hjkhsbnmn123", 100, "astaxie"} 22 | Objects["mjjkxsxsaa23"] = &Object{"mjjkxsxsaa23", 101, "someone"} 23 | } 24 | 25 | func AddOne(object Object) (ObjectId string) { 26 | object.ObjectId = "astaxie" + strconv.FormatInt(time.Now().UnixNano(), 10) 27 | Objects[object.ObjectId] = &object 28 | return object.ObjectId 29 | } 30 | 31 | func GetOne(ObjectId string) (object *Object, err error) { 32 | if v, ok := Objects[ObjectId]; ok { 33 | return v, nil 34 | } 35 | return nil, errors.New("ObjectId Not Exist") 36 | } 37 | 38 | func GetAll() map[string]*Object { 39 | return Objects 40 | } 41 | 42 | func Update(ObjectId string, Score int64) (err error) { 43 | if v, ok := Objects[ObjectId]; ok { 44 | v.Score = Score 45 | return nil 46 | } 47 | return errors.New("ObjectId Not Exist") 48 | } 49 | 50 | func Delete(ObjectId string) { 51 | delete(Objects, ObjectId) 52 | } 53 | 54 | -------------------------------------------------------------------------------- /models/userModel/user.go: -------------------------------------------------------------------------------- 1 | package userModel 2 | 3 | import ( 4 | "github.com/astaxie/beego/orm" 5 | "time" 6 | "github.com/astaxie/beego" 7 | "im_api/libs/define" 8 | ) 9 | 10 | const USER_DB = "test" 11 | 12 | func init() { 13 | 14 | } 15 | 16 | type User struct { 17 | Id string `orm:"pk"` 18 | UserName string `valid:"Required;MinSize(3);MaxSize(20)"` 19 | Password string `valid:"Required;MinSize(6);MaxSize(20)"` 20 | CreateTime int64 `data:"CreateTime"` 21 | UpdateTime int64 `data:"UpdateTime"` 22 | } 23 | 24 | type Auth struct { 25 | Auth string `valid:"Required;MinSize(3);MaxSize(20)"` 26 | } 27 | 28 | 29 | func GetOne(userId string) (User *User, err error) { 30 | o := orm.NewOrm() 31 | o.Using("default") // 默认使用 default,你可以指定为其他数据库 32 | 33 | return 34 | } 35 | 36 | func CheckoutUserNameExist(userName string) bool { 37 | o := orm.NewOrm() 38 | o.Using("default") // 默认使用 default,你可以指定为其他数据库 39 | user := User{UserName: userName} 40 | err := o.Read(&user, "UserName") 41 | if err == orm.ErrNoRows { 42 | return true 43 | } 44 | return false 45 | } 46 | 47 | func GetUserInfoByUserName(userName string) (user User) { 48 | o := orm.NewOrm() 49 | o.Using("default") // 默认使用 default,你可以指定为其他数据库 50 | user = User{UserName: userName} 51 | err := o.Read(&user, "UserName") 52 | if err == orm.ErrNoRows { 53 | return User{} 54 | } 55 | return user 56 | } 57 | 58 | func AddOne(user User) (code int, msg string) { 59 | o := orm.NewOrm() 60 | o.Using("default") // 默认使用 default,你可以指定为其他数据库 61 | 62 | user.CreateTime = time.Now().Unix() 63 | user.UpdateTime = time.Now().Unix() 64 | _, err := o.Insert(&user) 65 | if err != nil { 66 | code = define.ERR_MYSQL_EXCEPTION_CODE 67 | msg = define.ERR_MYSQL_EXCEPTION_MSG 68 | beego.Error("mysql insert err :%v", err) 69 | return 70 | } 71 | code = define.SUCCESS_CODE 72 | msg = define.SUCCESS_MSG 73 | return 74 | } 75 | -------------------------------------------------------------------------------- /module/config/config.go: -------------------------------------------------------------------------------- 1 | package config 2 | 3 | import ( 4 | "os" 5 | "github.com/astaxie/beego/config" 6 | ) 7 | 8 | func Reader(filePath string) (iniconf config.Configer, err error) { 9 | path, _ := os.Getwd() 10 | // path += "/../.." 11 | appconf, err := config.NewConfig("ini", path+"/conf/app.conf") 12 | if err != nil { 13 | return 14 | } 15 | runmode := appconf.String("runmode") 16 | if runmode == "dev" { 17 | iniconf, err = config.NewConfig("ini", path+"/conf/dev/"+filePath) 18 | } else { 19 | iniconf, err = config.NewConfig("ini", path+"/conf/prod/"+filePath) 20 | } 21 | return iniconf, err 22 | 23 | 24 | } -------------------------------------------------------------------------------- /module/redis/redis.go: -------------------------------------------------------------------------------- 1 | package redis 2 | 3 | import ( 4 | "github.com/astaxie/beego" 5 | "time" 6 | "github.com/go-redis/redis" 7 | "im_api/module/config" 8 | ) 9 | 10 | 11 | var ( 12 | Prefix string 13 | RedisCli *redis.Client 14 | ) 15 | 16 | func InitRedis() (err error) { 17 | config, err := config.Reader("database.conf") 18 | Prefix = config.String("redis::RedisPrefix") 19 | if err != nil { 20 | beego.Error("config reader err: %v", err) 21 | } 22 | db, err := config.Int("redis::RedisDefaultDB") 23 | if err != nil { 24 | beego.Error("Redis get db err: %s", err) 25 | return 26 | } 27 | 28 | RedisCli = redis.NewClient(&redis.Options{ 29 | Addr: config.String("redis::RedisAddr"), 30 | Password: config.String("redis::RedisPw"), // no password set 31 | DB: db, // use default DB 32 | }) 33 | beego.Debug("redis db %d", db) 34 | if pong, err := RedisCli.Ping().Result(); err != nil { 35 | beego.Error("RedisCli Ping Result pong: %s, err: %s", pong, err) 36 | 37 | } 38 | return 39 | } 40 | 41 | 42 | func Get(key string) string{ 43 | beego.Debug("redis get key %s", GetKey(key)) 44 | return RedisCli.Get(GetKey(key)).Val() 45 | } 46 | 47 | func HGet(key string, field string ) string{ 48 | // beego.Debug("redis get key %s", GetKey(key)) 49 | return RedisCli.HGet(GetKey(key), field).Val() 50 | 51 | } 52 | 53 | func HGetAll(key string) (map[string]string, error) { 54 | return RedisCli.HGetAll(GetKey(key)).Result() 55 | } 56 | 57 | func Set(key string, val interface{}, expiration time.Duration) ( err error) { 58 | err = RedisCli.Set(GetKey(key), val, expiration).Err() 59 | return 60 | } 61 | 62 | 63 | func Delete(key string) error { 64 | return RedisCli.Del(GetKey(key)).Err() 65 | 66 | } 67 | 68 | func GetKey(key string) string { 69 | beego.Debug("redis get Prefix %s",Prefix) 70 | return Prefix + key 71 | } 72 | 73 | func HMSet(key string, mapData map[string]interface{}) (err error){ 74 | err = RedisCli.HMSet(GetKey(key), mapData).Err() 75 | return 76 | 77 | } 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /module/util/util.go: -------------------------------------------------------------------------------- 1 | package util 2 | 3 | import ( 4 | 5 | 6 | "github.com/satori/go.uuid" 7 | "strings" 8 | "encoding/json" 9 | "fmt" 10 | "crypto/md5" 11 | ) 12 | 13 | func GenUuid() string { 14 | uuidStr := uuid.Must(uuid.NewV4()).String() 15 | uuidStr = strings.Replace(uuidStr, "-", "", -1) 16 | uuidByt := []rune(uuidStr) 17 | return string(uuidByt[8:24]) 18 | } 19 | 20 | func JsonEncode(structModel interface{}) (string, error) { 21 | jsonStr, err := json.Marshal(structModel) 22 | return string(jsonStr), err 23 | } 24 | func JsonDecode(jsonStr string, structModel interface{}) error { 25 | decode := json.NewDecoder(strings.NewReader(jsonStr)) 26 | err := decode.Decode(structModel) 27 | return err 28 | } 29 | 30 | func Md5(str string) string { 31 | data := []byte(str) 32 | return fmt.Sprintf("%x", md5.Sum(data)) 33 | } -------------------------------------------------------------------------------- /routers/router.go: -------------------------------------------------------------------------------- 1 | // @APIVersion 1.0.0 2 | // @Title beego Test API 3 | // @Description beego has a very cool tools to autogenerate documents for your API 4 | // @Contact astaxie@gmail.com 5 | // @TermsOfServiceUrl http://beego.me/ 6 | // @License Apache 2.0 7 | // @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html 8 | package routers 9 | 10 | import ( 11 | "github.com/astaxie/beego" 12 | "im_api/controllers/user" 13 | 14 | "im_api/controllers" 15 | ) 16 | 17 | func init() { 18 | ns := beego.NewNamespace("/v1", 19 | beego.NSNamespace("/object", 20 | beego.NSInclude( 21 | &controllers.ObjectController{}, 22 | ), 23 | ), 24 | beego.NSNamespace("/user", 25 | beego.NSInclude( 26 | &user.UserController{}, 27 | ), 28 | ), 29 | 30 | ) 31 | beego.AddNamespace(ns) 32 | // beego.Router("/user", &controllers.UserController{}) 33 | 34 | } 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /tests/default_test.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "net/http" 5 | "net/http/httptest" 6 | "testing" 7 | "runtime" 8 | "path/filepath" 9 | _ "im_api/routers" 10 | 11 | "github.com/astaxie/beego" 12 | . "github.com/smartystreets/goconvey/convey" 13 | ) 14 | 15 | func init() { 16 | _, file, _, _ := runtime.Caller(1) 17 | apppath, _ := filepath.Abs(filepath.Dir(filepath.Join(file, ".." + string(filepath.Separator)))) 18 | beego.TestBeegoInit(apppath) 19 | } 20 | 21 | // TestGet is a sample to run an endpoint test 22 | func TestGet(t *testing.T) { 23 | r, _ := http.NewRequest("GET", "/v1/object", nil) 24 | w := httptest.NewRecorder() 25 | beego.BeeApp.Handlers.ServeHTTP(w, r) 26 | 27 | beego.Trace("testing", "TestGet", "Code[%d]\n%s", w.Code, w.Body.String()) 28 | 29 | Convey("Subject: Test Station Endpoint\n", t, func() { 30 | Convey("Status Code Should Be 200", func() { 31 | So(w.Code, ShouldEqual, 200) 32 | }) 33 | Convey("The Result Should Not Be Empty", func() { 34 | So(w.Body.Len(), ShouldBeGreaterThan, 0) 35 | }) 36 | }) 37 | } 38 | 39 | --------------------------------------------------------------------------------