Browse Source

new frame

zjxpcyc 6 years ago
parent
commit
128b4de8f5

+ 2
- 0
.gitignore View File

@@ -0,0 +1,2 @@
1
+*.exe
2
+*.exe~

+ 5
- 0
conf/aliyun.conf View File

@@ -0,0 +1,5 @@
1
+[oss]
2
+Endpoint=oss-cn-shanghai.aliyuncs.com
3
+AccessKeyId=LTAIkc75dpkJw8Lb
4
+AccessKeySecret=v4bvXCaix6vSDTCFfwSAdqV53iFEQw
5
+Bucket=jingcheng-h5temp

+ 19
- 3
conf/app.conf View File

@@ -1,6 +1,22 @@
1
-appname = spaceofcheng
2
-httpport = 8777
1
+appname = services
2
+httpport = 8080
3 3
 runmode = dev
4
+autorender = false
5
+copyrequestbody = true
6
+EnableDocs = true
4 7
 sessionon = true
5 8
 
6
-ApiPrefix = /api
9
+
10
+[cros]
11
+allowMode = dev
12
+allowCredentials = true
13
+allowOrigin = http://localhost:9528
14
+
15
+# GET, POST etc
16
+allowMethods = *
17
+
18
+[api]
19
+prefix = "/api"
20
+guest = "/guest"
21
+common = "/common"
22
+wechat = "/wechat"

+ 3
- 3
conf/db.conf View File

@@ -11,10 +11,10 @@ db_addr      = localhost
11 11
 db_port      = 3306
12 12
 
13 13
 ; 用户名
14
-username     = h5-template
14
+username     = spaceofcheng
15 15
 
16 16
 ; 密码
17
-password     = h5-template
17
+password     = spaceofcheng
18 18
 
19 19
 ; 数据库名或者schema
20 20
 database     = spaceofcheng
@@ -26,4 +26,4 @@ dbprefix     =
26 26
 db_debug     = false
27 27
 
28 28
 ; 字符集
29
-char_set     = utf8mb4
29
+char_set     = utf8

+ 40
- 0
controllers/auth.go View File

@@ -0,0 +1,40 @@
1
+package controllers
2
+
3
+import (
4
+	"strings"
5
+
6
+	"github.com/astaxie/beego"
7
+)
8
+
9
+// Authenticate 权限验证
10
+func (c *BaseController) authenticate() {
11
+	if !c.needAuth() {
12
+		return
13
+	}
14
+
15
+	userID, _ := c.GetSession(SNUserID).(string)
16
+	// userType := c.GetSession(SNUserType).(string)
17
+
18
+	// 未登录状态
19
+	if userID == "" {
20
+		return
21
+	}
22
+
23
+	// clientType := utils.GetClientType()
24
+	// if clientType == utils.ClientWechat {
25
+
26
+	// }
27
+
28
+}
29
+
30
+func (c *BaseController) needAuth() bool {
31
+	route := c.Ctx.Input.URL()
32
+	apiPrefix := beego.AppConfig.String("api::prefix")
33
+	guestAPI := beego.AppConfig.String("api::guest")
34
+
35
+	if strings.Index(route, apiPrefix+guestAPI) > -1 {
36
+		return false
37
+	}
38
+
39
+	return true
40
+}

+ 47
- 57
controllers/base.go View File

@@ -2,100 +2,90 @@ package controllers
2 2
 
3 3
 import (
4 4
 	"net/http"
5
-	"reflect"
6
-	"space-of-cheng/helper"
7
-	"space-of-cheng/models"
5
+	"spaceofcheng/services/utils"
8 6
 
9 7
 	"github.com/astaxie/beego"
10
-	"github.com/yl10/kit/orm"
11 8
 )
12 9
 
13
-//Message api统一的返回消息格式
14
-type Message struct {
15
-	Code    int         `json:"code"`
16
-	Message interface{} `json:"message"`
17
-}
18
-
19 10
 //BaseController 基础controller
20 11
 type BaseController struct {
21 12
 	beego.Controller
22
-	Context *helper.Context
23
-}
24
-
25
-// BaseControllerInterface 项目约定的 Controller 须满足的接口
26
-type BaseControllerInterface interface {
27
-	Constructor()
13
+	Context *utils.Context
28 14
 }
29 15
 
30 16
 //Prepare 继承beego的
31 17
 func (c *BaseController) Prepare() {
32 18
 	// 初始化上下文
33 19
 	c.initContext()
34
-	c.Context.Ready(nil)
20
+
21
+	// 鉴权
22
+	c.authenticate()
35 23
 
36 24
 	// 路由对应的实际 Controller 初始化
37 25
 	c.initController()
38 26
 }
39 27
 
40
-// ResponseJson 自定义的JSON返回
41
-func (c *BaseController) ResponseJson(msg interface{}, code ...int) {
28
+// ResponseJSON 返回JSON数据
29
+func (c *BaseController) ResponseJSON(data interface{}) {
30
+	c.ResponseData(data, "")
31
+}
32
+
33
+// ResponseError 返回错误
34
+func (c *BaseController) ResponseError(err error, code ...int) {
35
+	c.ResponseData(nil, err, code...)
36
+}
37
+
38
+// ResponseData 自定义的JSON返回
39
+func (c *BaseController) ResponseData(data interface{}, msg interface{}, code ...int) {
42 40
 	status := http.StatusOK
43 41
 	if len(code) > 0 {
44 42
 		status = code[0]
45 43
 	}
46 44
 
47
-	if status < http.StatusMultipleChoices {
48
-		c.Context.Commit()
49
-	} else {
50
-		c.Context.RollBack()
51
-	}
52
-
53
-	c.Context.Destroy()
45
+	c.destroyContext(status < http.StatusMultipleChoices)
54 46
 
55
-	if reflect.ValueOf(msg).Type().String() == "*errors.errorString" {
56
-		err := msg.(error)
57
-		c.Data["json"] = Message{status, err.Error()}
58
-	} else {
59
-		c.Data["json"] = Message{status, msg}
47
+	sendMessage := ""
48
+	switch msgVal := msg.(type) {
49
+	case error:
50
+		sendMessage = msgVal.Error()
51
+	case string:
52
+		sendMessage = msgVal
53
+	default:
54
+		sendMessage = ""
60 55
 	}
61 56
 
57
+	c.Data["json"] = JSONMessage{status, sendMessage, data}
58
+	c.Ctx.Output.Header("Access-Control-Expose-Headers", "X-Token")
59
+
60
+	c.crosPolicy()
62 61
 	c.ServeJSON()
63 62
 	c.StopRun()
64 63
 }
65 64
 
66
-// ResponseRaw 返回
67
-func (c *BaseController) ResponseRaw(msg []byte) {
68
-	c.Ctx.ResponseWriter.Write(msg)
69
-	c.Context.Commit()
70
-	c.Context.Destroy()
71
-
72
-	c.StopRun()
65
+// Options 解决跨域先发送 options
66
+func (c *BaseController) Options() {
67
+	c.ResponseJSON("")
73 68
 }
74 69
 
75
-// initContext 初始化 Context
76
-func (c *BaseController) initContext() {
77
-	// 分页设置
78
-	pageSetting := map[string]int{
79
-		"pageNum": 100,
70
+// crosPolicy 跨域策略
71
+func (c *BaseController) crosPolicy() {
72
+	runMode := beego.AppConfig.String("runmode")
73
+	allowMode := beego.AppConfig.String("cros::allowMode")
74
+	allowMethods := beego.AppConfig.String("cros::allowMethods")
75
+	allowOrigin := beego.AppConfig.String("cros::allowOrigin")
76
+	allowCredentials := beego.AppConfig.String("cros::allowCredentials")
77
+
78
+	if runMode == allowMode {
79
+		c.Ctx.Output.Header("Access-Control-Allow-Origin", allowOrigin)
80
+		c.Ctx.Output.Header("Access-Control-Allow-Methods", allowMethods)
81
+		c.Ctx.Output.Header("Access-Control-Allow-Credentials", allowCredentials)
82
+		c.Ctx.Output.Header("Access-Control-Allow-Headers", "X-Token,Authorization")
80 83
 	}
81
-	// 初始化 orm
82
-	o, _ := orm.NewXormPlus(models.Dao.NewSession())
83
-	o.SetPageNavi(pageSetting)
84
-
85
-	c.Context = helper.NewContext(o, nil)
86 84
 }
87 85
 
88 86
 // initAppController 执行当前路由请求对应的 Controller 初始化
89 87
 func (c *BaseController) initController() {
90
-	if ctrl, ok := c.AppController.(BaseControllerInterface); ok {
88
+	if ctrl, ok := c.AppController.(ControllerInterface); ok {
91 89
 		ctrl.Constructor()
92 90
 	}
93 91
 }
94
-
95
-// Options 解决跨域先发送 options
96
-func (c *BaseController) Options() {
97
-	c.ResponseJson(map[string]interface{}{
98
-		"Status":  true,
99
-		"Message": "ok",
100
-	})
101
-}

+ 34
- 0
controllers/context.go View File

@@ -0,0 +1,34 @@
1
+package controllers
2
+
3
+import (
4
+	"spaceofcheng/services/models"
5
+	"spaceofcheng/services/utils"
6
+)
7
+
8
+/**
9
+* Context 说明
10
+* - 所有 stuct 类型均不是指针
11
+* - 包含内容如下
12
+* user					用户基本信息
13
+* customer			会员基本信息
14
+* cases					用户所有案场信息
15
+* currentCase 	当前案场
16
+* org						用户当前组织
17
+**/
18
+
19
+// initContext 初始化 Context
20
+func (c *BaseController) initContext() {
21
+	c.Context = utils.NewContext(models.DBEngine, nil)
22
+	c.Context.Ready()
23
+}
24
+
25
+// initContext 销毁 Context
26
+func (c *BaseController) destroyContext(ok ...bool) {
27
+	if len(ok) == 0 || ok[0] {
28
+		c.Context.DB.Rollback()
29
+	} else {
30
+		c.Context.DB.Commit()
31
+	}
32
+
33
+	c.Context.Destroy()
34
+}

+ 49
- 0
controllers/file.go View File

@@ -0,0 +1,49 @@
1
+package controllers
2
+
3
+import (
4
+	"spaceofcheng/services/utils"
5
+	"strconv"
6
+	"time"
7
+
8
+	"net/http"
9
+
10
+	"github.com/astaxie/beego/config"
11
+)
12
+
13
+// FileUpload 文件上传
14
+func (c *BaseController) FileUpload() {
15
+	file, err := c.uploadFileToOSS("file")
16
+	if err != nil {
17
+		c.ResponseError(err, http.StatusInternalServerError)
18
+	}
19
+
20
+	c.ResponseJSON(map[string]interface{}{
21
+		"url": file,
22
+	})
23
+}
24
+
25
+func (c *BaseController) uploadFileToOSS(field string) (string, error) {
26
+	aliConf, err := config.NewConfig("ini", "conf/aliyun.conf")
27
+	if err != nil {
28
+		return "", err
29
+	}
30
+
31
+	endpoint := aliConf.String("oss::Endpoint")
32
+	accessKeyID := aliConf.String("oss::AccessKeyId")
33
+	accessKeySecret := aliConf.String("oss::AccessKeySecret")
34
+	bucket := aliConf.String("oss::Bucket")
35
+
36
+	aliCli, err := utils.GetOssClient(endpoint, accessKeyID, accessKeySecret)
37
+	if err != nil {
38
+		return "", err
39
+	}
40
+
41
+	fNameExtra := strconv.FormatInt(time.Now().Unix(), 10)
42
+
43
+	fileURL, err := utils.UploadFileToBucket(aliCli, c.Ctx.Request, bucket, field, fNameExtra)
44
+	if err != nil {
45
+		return "", err
46
+	}
47
+
48
+	return fileURL, nil
49
+}

+ 9
- 0
controllers/session.go View File

@@ -0,0 +1,9 @@
1
+package controllers
2
+
3
+// session key 列表
4
+const (
5
+	// 用户ID
6
+	SNUserID = "userid"
7
+	// 用户类型
8
+	SNUserType = "userType"
9
+)

+ 20
- 0
controllers/types.go View File

@@ -0,0 +1,20 @@
1
+package controllers
2
+
3
+// 用户类型列表
4
+const (
5
+	UserGuest    = "guest"
6
+	UserCommon   = "common"
7
+	UserCustomer = "customer"
8
+)
9
+
10
+// JSONMessage 主要用于 Response 返回
11
+type JSONMessage struct {
12
+	Code    int         `json:"code"`
13
+	Message string      `json:"message"`
14
+	Result  interface{} `json:"result"`
15
+}
16
+
17
+// ControllerInterface 项目约定的 Controller 须满足的接口
18
+type ControllerInterface interface {
19
+	Constructor()
20
+}

+ 0
- 24
helper/clienttype.go View File

@@ -1,24 +0,0 @@
1
-package helper
2
-
3
-import "strings"
4
-
5
-const (
6
-	CLIENT_PC     = "PC"
7
-	CLIENT_MOBILE = "Mobile"
8
-	CLIENT_WECHAT = "Wechat"
9
-)
10
-
11
-func GetClientType(ua string) string {
12
-	tp := CLIENT_PC
13
-
14
-	ua = strings.ToLower(ua)
15
-
16
-	if strings.Index(ua, "mobile") > -1 {
17
-		tp = CLIENT_MOBILE
18
-	}
19
-	if strings.Index(ua, "micromessenger") > -1 {
20
-		tp = CLIENT_WECHAT
21
-	}
22
-
23
-	return tp
24
-}

+ 0
- 105
helper/context.go View File

@@ -1,105 +0,0 @@
1
-package helper
2
-
3
-import (
4
-	"github.com/yl10/kit/orm"
5
-)
6
-
7
-// Context 上下文
8
-// 只限制在每次 Request 内
9
-type Context struct {
10
-	db      *orm.XormPlus
11
-	options map[string]interface{}
12
-	User    interface{}
13
-}
14
-
15
-// NewContext 初始化上下文
16
-func NewContext(db *orm.XormPlus, opt map[string]interface{}) *Context {
17
-	return &Context{
18
-		db:      db,
19
-		options: opt,
20
-	}
21
-}
22
-
23
-// Ready Request 级别初始化
24
-func (c *Context) Ready(options map[string]interface{}) error {
25
-	if options != nil {
26
-		c.options = options
27
-	}
28
-
29
-	// 自动提交, 默认是否
30
-	autoCommit, _ := c.getOption("autoCommit", false).(bool)
31
-	if !autoCommit {
32
-		// 开启事务
33
-		if err := c.openDBTransaction(); err != nil {
34
-			return err
35
-		}
36
-	}
37
-
38
-	return nil
39
-}
40
-
41
-// Destroy 析构函数
42
-func (c *Context) Destroy() {
43
-	// 自动提交, 默认是否
44
-	autoCommit, _ := c.getOption("autoCommit", false).(bool)
45
-	if !autoCommit {
46
-		c.closeDBTransaction()
47
-	} else {
48
-		c.db.Close()
49
-	}
50
-}
51
-
52
-// Commit 提交
53
-func (c *Context) Commit() error {
54
-	return c.db.Commit()
55
-}
56
-
57
-// RollBack 回滚
58
-func (c *Context) RollBack() error {
59
-	return c.db.Rollback()
60
-}
61
-
62
-// GetDB 获取数据库操作实例
63
-func (c *Context) GetDB() *orm.XormPlus {
64
-	return c.db
65
-}
66
-
67
-// SetDB 设置数据库操作实例
68
-func (c *Context) SetDB(db *orm.XormPlus) *Context {
69
-	c.db = db
70
-	return c
71
-}
72
-
73
-// openDBTransaction 开启事务
74
-func (c *Context) openDBTransaction() error {
75
-	// 开启写事务
76
-	if err := c.db.Begin(); err != nil {
77
-		return err
78
-	}
79
-
80
-	return nil
81
-}
82
-
83
-// closeDBTransaction 关闭事务
84
-// 注意, 事务关闭后, DB 将不能再使用
85
-func (c *Context) closeDBTransaction() error {
86
-	// 自动提交, 默认是否
87
-	autoCommit, _ := c.getOption("autoCommit", false).(bool)
88
-
89
-	if !autoCommit {
90
-		c.db.Close()
91
-	}
92
-
93
-	return nil
94
-}
95
-
96
-// getOption 读取配置项
97
-func (c *Context) getOption(key string, def interface{}) interface{} {
98
-	if c.options != nil {
99
-		if opt, has := c.options[key]; has {
100
-			return opt
101
-		}
102
-	}
103
-
104
-	return def
105
-}

+ 0
- 18
helper/error.go View File

@@ -1,18 +0,0 @@
1
-package helper
2
-
3
-import (
4
-	"errors"
5
-
6
-	"github.com/astaxie/beego"
7
-)
8
-
9
-// LogError 错误日志
10
-func LogError(err string, v ...interface{}) error {
11
-	beego.Error(err)
12
-
13
-	if len(v) > 0 {
14
-		beego.Error(v...)
15
-	}
16
-
17
-	return errors.New(err)
18
-}

+ 5
- 3
main.go View File

@@ -1,13 +1,15 @@
1 1
 package main
2 2
 
3 3
 import (
4
-	_ "cdkj-check/routers"
4
+	_ "spaceofcheng/services/routers"
5 5
 
6 6
 	"github.com/astaxie/beego"
7 7
 )
8 8
 
9 9
 func main() {
10
-
11
-	beego.InsertFilter("/*", beego.BeforeExec, accessLog)
10
+	if beego.BConfig.RunMode == "dev" {
11
+		beego.BConfig.WebConfig.DirectoryIndex = true
12
+		beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
13
+	}
12 14
 	beego.Run()
13 15
 }

+ 8
- 13
models/models.go View File

@@ -7,42 +7,37 @@ import (
7 7
 )
8 8
 
9 9
 var (
10
-	Dao *xorm.Engine
10
+	DBEngine *xorm.Engine
11 11
 )
12 12
 
13 13
 func init() {
14
-	Dao = NewDAO()
14
+	DBEngine = NewDBEngine()
15 15
 }
16 16
 
17
-// NewDAO 初始化数据库连接
18
-func NewDAO() *xorm.Engine {
17
+// NewDBEngine 初始化数据库连接
18
+func NewDBEngine() *xorm.Engine {
19 19
 	dbType := "mysql"
20
-	dns := getMysqlDns()
20
+	dns := getMySQLDNS()
21 21
 
22
-	dao, err := xorm.NewEngine(dbType, dns)
22
+	engine, err := xorm.NewEngine(dbType, dns)
23 23
 	// dao.ShowSQL()
24 24
 
25 25
 	if err != nil {
26 26
 		panic(err)
27
-		return nil
28 27
 	}
29 28
 
30
-	Dao = dao
31
-	return dao
29
+	return engine
32 30
 }
33 31
 
34
-func getMysqlDns() string {
32
+func getMySQLDNS() string {
35 33
 	dbconf, _ := config.NewConfig("ini", "conf/db.conf")
36 34
 
37
-	// db_type  := dbconf.DefaultString("db_type", "mysql")
38 35
 	conProt := dbconf.DefaultString("con_protocol", "tcp")
39 36
 	dbAddr := dbconf.DefaultString("db_addr", "localhost")
40 37
 	dbPort := dbconf.DefaultString("db_port", "3306")
41 38
 	userName := dbconf.DefaultString("username", "root")
42 39
 	password := dbconf.String("password")
43 40
 	database := dbconf.String("database")
44
-	// dbprefix := dbconf.String("dbprefix")
45
-	// db_debug := dbconf.DefaultBool("db_debug", false)
46 41
 	charSet := dbconf.DefaultString("char_set", "utf8")
47 42
 
48 43
 	dns := userName

+ 21
- 0
models/sys.go View File

@@ -0,0 +1,21 @@
1
+package models
2
+
3
+import (
4
+	"spaceofcheng/services/utils"
5
+
6
+	"github.com/go-xorm/xorm"
7
+)
8
+
9
+// SysDAO 系统
10
+type SysDAO struct {
11
+	ctx *utils.Context
12
+	db  *xorm.Session
13
+}
14
+
15
+// NewSysDAO New Inst
16
+func NewSysDAO(ctx *utils.Context) *SysDAO {
17
+	return &SysDAO{
18
+		ctx: ctx,
19
+		db:  ctx.DB,
20
+	}
21
+}

+ 0
- 1
models/system/user.go View File

@@ -1 +0,0 @@
1
-package system

+ 21
- 0
models/user.go View File

@@ -0,0 +1,21 @@
1
+package models
2
+
3
+import (
4
+	"spaceofcheng/services/utils"
5
+
6
+	"github.com/go-xorm/xorm"
7
+)
8
+
9
+// UserDAO 系统
10
+type UserDAO struct {
11
+	ctx *utils.Context
12
+	db  *xorm.Session
13
+}
14
+
15
+// NewUserDAO New Inst
16
+func NewUserDAO(ctx *utils.Context) *UserDAO {
17
+	return &UserDAO{
18
+		ctx: ctx,
19
+		db:  ctx.DB,
20
+	}
21
+}

+ 0
- 31
plugins.go View File

@@ -1,31 +0,0 @@
1
-package main
2
-
3
-import (
4
-	"github.com/astaxie/beego/context"
5
-)
6
-
7
-func accessLog(ctx *context.Context) {
8
-	// plugin := func(ctx *context.Context) {
9
-	// 	access := model.TaApiAccessLog{
10
-	// 		Protocal: ctx.Input.Protocol(),
11
-	// 		Schema:   ctx.Input.Scheme(),
12
-	// 		Host:     ctx.Input.Host(),
13
-	// 		Uri:      ctx.Input.URI(),
14
-	// 		Port:     ctx.Input.Port(),
15
-	// 		Referer:  ctx.Input.Referer(),
16
-	// 		Ip:       ctx.Input.IP(),
17
-	// 		Ua:       ctx.Input.UserAgent(),
18
-	// 		Method:   ctx.Input.Method(),
19
-	// 	}
20
-
21
-	// 	if strings.Index(access.Ua, "mobile") > 0 {
22
-	// 		access.ClientType = accLog.CLIENT_MOBILE
23
-	// 	}
24
-
25
-	// 	dao := accLog.NewDAO(nil)
26
-	// 	dao.SaveAccessLog(&access)
27
-	// }
28
-
29
-	// // 不影响主进程
30
-	// go plugin(ctx)
31
-}

+ 0
- 0
readme.md View File


+ 15
- 0
routers/common.go View File

@@ -0,0 +1,15 @@
1
+package routers
2
+
3
+import (
4
+	"spaceofcheng/services/controllers"
5
+
6
+	"github.com/astaxie/beego"
7
+)
8
+
9
+func getCommonRoutes() beego.LinkNamespace {
10
+	prefix := beego.AppConfig.String("api::common")
11
+
12
+	return beego.NSNamespace(prefix,
13
+		beego.NSRouter("/file", &controllers.BaseController{}, "post:FileUpload"),
14
+	)
15
+}

+ 1
- 0
routers/guest.go View File

@@ -0,0 +1 @@
1
+package routers

+ 18
- 7
routers/router.go View File

@@ -1,17 +1,28 @@
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
1 8
 package routers
2 9
 
3 10
 import (
4
-	"tolet/controllers"
11
+	"spaceofcheng/services/controllers"
5 12
 
6 13
 	"github.com/astaxie/beego"
7 14
 )
8 15
 
9 16
 func init() {
10
-	beego.Router("/*", &controllers.BaseController{}, "options:Options")
17
+	prefix := beego.AppConfig.String("api::prefix")
11 18
 
12
-	// apiPrefix := beego.AppConfig.String("ApiPrefix")
13
-	// ns := beego.NewNamespace(apiPrefix,
14
-	// 	beego.NSRouter("/GetCheckByUser", &bodycheck.BodyCheckController{}, "get:GetCheckByUser"),
15
-	// )
16
-	// beego.AddNamespace(ns)
19
+	ns := beego.NewNamespace(prefix,
20
+		// 解决跨域时 先发送 options 问题
21
+		beego.NSRouter("*", &controllers.BaseController{}, "options:Options"),
22
+
23
+		// 通用需要鉴权路由
24
+		getCommonRoutes(),
25
+	)
26
+
27
+	beego.AddNamespace(ns)
17 28
 }

+ 1
- 0
routers/wechat.go View File

@@ -0,0 +1 @@
1
+package routers

+ 4
- 0
service/events.go View File

@@ -0,0 +1,4 @@
1
+package service
2
+
3
+// EventServ 事件 Serv
4
+type EventServ struct{}

+ 1
- 0
service/service.go View File

@@ -0,0 +1 @@
1
+package service

+ 24
- 0
service/sys.go View File

@@ -0,0 +1,24 @@
1
+package service
2
+
3
+import (
4
+	"spaceofcheng/services/models"
5
+	"spaceofcheng/services/utils"
6
+)
7
+
8
+// SysServ 系统处理
9
+type SysServ struct {
10
+	ctx *utils.Context
11
+	dao *models.SysDAO
12
+}
13
+
14
+// NewSysServ 初始化
15
+func NewSysServ(ctx *utils.Context) *SysServ {
16
+	return &SysServ{
17
+		ctx: ctx,
18
+		dao: models.NewSysDAO(ctx),
19
+	}
20
+}
21
+
22
+func (s *SysServ) GetUserByID(id string) error {
23
+	return nil
24
+}

+ 104
- 0
utils/aliyun.go View File

@@ -0,0 +1,104 @@
1
+package utils
2
+
3
+import (
4
+	"bytes"
5
+	"encoding/base64"
6
+	"net/http"
7
+	"strings"
8
+	"time"
9
+
10
+	"github.com/yl10/kit/guid"
11
+
12
+	"github.com/aliyun/aliyun-oss-go-sdk/oss"
13
+)
14
+
15
+// GetOssClient 获取 OSS 客户端
16
+func GetOssClient(endpoint, accessKeyID, accessKeySecret string) (*oss.Client, error) {
17
+	return oss.New(endpoint, accessKeyID, accessKeySecret)
18
+}
19
+
20
+// UploadFileToBucket 简单上传文件
21
+func UploadFileToBucket(cli *oss.Client, req *http.Request, bucket, fromFront string, nameSuffix ...string) (string, error) {
22
+	bkt, err := cli.Bucket(bucket)
23
+	if err != nil {
24
+		return "", err
25
+	}
26
+
27
+	file, fh, err := req.FormFile(fromFront)
28
+	if err != nil {
29
+		return "", err
30
+	}
31
+	defer file.Close()
32
+
33
+	fname := fh.Filename
34
+	if len(nameSuffix) > 0 && nameSuffix[0] != "" {
35
+		fArr := strings.Split(fname, ".")
36
+		fArr[0] = fArr[0] + nameSuffix[0]
37
+		fname = strings.Join(fArr, ".")
38
+	}
39
+
40
+	err = bkt.PutObject(fname, file)
41
+	if err != nil {
42
+		return "", err
43
+	}
44
+
45
+	return strings.Join([]string{
46
+		"http://",
47
+		bucket + ".",
48
+		cli.Config.Endpoint + "/",
49
+		fname,
50
+	}, ""), nil
51
+}
52
+
53
+// UploadStringToBucket 上传base64图片
54
+func UploadStringToBucket(cli *oss.Client, bucket, fromStr string) (string, error) {
55
+	bkt, err := cli.Bucket(bucket)
56
+	if err != nil {
57
+		return "", err
58
+	}
59
+
60
+	imgName := guid.NewGUIDString() + "-" + time.Now().Local().Format("20060102150405")
61
+	imgExt := ".jpg"
62
+	switch getMIMEFromBase64(fromStr) {
63
+	case "image/gif":
64
+		imgExt = ".gif"
65
+	case "image/bmp":
66
+		imgExt = ".bmp"
67
+	case "image/png", "image/x-png":
68
+		imgExt = ".png"
69
+	case "image/pipeg":
70
+		imgExt = ".jfif"
71
+	case "image/webp":
72
+		imgExt = ".webp"
73
+	}
74
+
75
+	fName := imgName + imgExt
76
+
77
+	imgData, err := base64.StdEncoding.DecodeString(strings.Split(fromStr, "base64,")[1])
78
+	if err != nil {
79
+		return "", err
80
+	}
81
+
82
+	err = bkt.PutObject(fName, bytes.NewBuffer(imgData))
83
+	if err != nil {
84
+		return "", err
85
+	}
86
+
87
+	return strings.Join([]string{
88
+		"http://",
89
+		bucket + ".",
90
+		cli.Config.Endpoint + "/",
91
+		fName,
92
+	}, ""), nil
93
+}
94
+
95
+// utils
96
+// getMIMEFromBase64 获取 base64 字串中的 mime
97
+func getMIMEFromBase64(str string) string {
98
+	g := strings.Split(str, ";")
99
+	if len(g) < 2 {
100
+		return ""
101
+	}
102
+
103
+	return strings.ToLower(strings.TrimLeft(g[0], "data:"))
104
+}

+ 59
- 0
utils/context.go View File

@@ -0,0 +1,59 @@
1
+package utils
2
+
3
+import (
4
+	"github.com/go-xorm/xorm"
5
+)
6
+
7
+// Context 上下文
8
+// 只限制在每次 Request 内
9
+type Context struct {
10
+	DB  *xorm.Session
11
+	box map[string]interface{}
12
+}
13
+
14
+// NewContext 初始化上下文
15
+func NewContext(engine *xorm.Engine, opt map[string]interface{}) *Context {
16
+	return &Context{
17
+		DB:  engine.NewSession(),
18
+		box: opt,
19
+	}
20
+}
21
+
22
+// Get 获取
23
+func (c *Context) Get(key string, def ...interface{}) interface{} {
24
+	if c.box != nil {
25
+		if opt, has := c.box[key]; has {
26
+			return opt
27
+		}
28
+	}
29
+
30
+	if len(def) > 0 {
31
+		return def[0]
32
+	}
33
+
34
+	return nil
35
+}
36
+
37
+// Set 设置
38
+func (c *Context) Set(key string, val interface{}) {
39
+	if c.box == nil {
40
+		c.box = make(map[string]interface{})
41
+	}
42
+
43
+	c.box[key] = val
44
+}
45
+
46
+// Ready Request 级别初始化
47
+func (c *Context) Ready() error {
48
+	// 开启事务
49
+	if err := c.DB.Begin(); err != nil {
50
+		return err
51
+	}
52
+
53
+	return nil
54
+}
55
+
56
+// Destroy 析构函数
57
+func (c *Context) Destroy() {
58
+	c.DB.Close()
59
+}

+ 13
- 0
utils/utils.go View File

@@ -0,0 +1,13 @@
1
+package utils
2
+
3
+// 客户端类型
4
+const (
5
+	ClientAdmin  = "client-admin"
6
+	ClientWechat = "client-wechat"
7
+	ClientMini   = "client-mini"
8
+)
9
+
10
+// GetClientType 获取客户端类型
11
+func GetClientType() string {
12
+	return ""
13
+}