Skip to content

Commit

Permalink
实现命令模式和访问者模式
Browse files Browse the repository at this point in the history
  • Loading branch information
carlo committed Jun 30, 2020
1 parent 00f00c3 commit 6b9e998
Show file tree
Hide file tree
Showing 12 changed files with 172 additions and 66 deletions.
20 changes: 18 additions & 2 deletions cmd/logic.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,12 @@ limitations under the License.
package cmd

import (
"fmt"
"context"
"github.com/gin-gonic/gin"
"github.com/wudaoluo/golog"
"github.com/wudaoluo/sonic/common"
v1 "github.com/wudaoluo/sonic/endpoint/v1"
"github.com/wudaoluo/sonic/service"

"github.com/spf13/cobra"
)
Expand All @@ -32,7 +37,18 @@ Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("logic called")
golog.Info("logic service start...")
service.NewLogicService().Start(context.Background())

router := gin.Default()

v1.LogicV1Router(router)

err := router.Run(common.GetConf().Logic.Addr)
if err != nil {
golog.Error("auth service start faild","err",err)
panic(err)
}
},
}

Expand Down
58 changes: 20 additions & 38 deletions common/command.go
Original file line number Diff line number Diff line change
@@ -1,64 +1,46 @@
package common


type CmdType int

func (c CmdType) String() string {
var value string
switch c {
case MsgReceive:
value = "msg_receive"
case MsgSend:
value = "msg_send"
default:
value = "not found"
}
return value
}

const (
MsgReceive CmdType = iota + 1 //消息接受
MsgSend //消息发送
ContactPersonList //联系人列表
MsgTotalUnRead //总未读书
MsgUnRead //消息未读数

import (
"encoding/json"
"github.com/wudaoluo/golog"
"github.com/wudaoluo/sonic/model"
)


var Cmd = &CommandHandler{CmdMap: make(map[CmdType]Command)}
var Cmd = &CommandHandler{CmdMap: make(map[model.CmdType]Command)}

// 命令接口
type Command interface {
Do(args interface{}) (interface{}, error)
}

// 上下文
type CmdContext struct {
CmdType CmdType
Args interface{}
}

// 命令管理者
type CommandHandler struct {
CmdMap map[CmdType]Command
CmdMap map[model.CmdType]Command
}

// 处理命令
func (ch *CommandHandler) Handle(ctx *CmdContext) (interface{}, error) {
if ctx == nil {
func (ch *CommandHandler) Handle(buf []byte) (interface{}, error) {
if buf == nil {
return nil, COMMAND_NIL
}
cmd, ok := ch.CmdMap[ctx.CmdType]

var param model.LogicCommand
err := json.Unmarshal(buf,&param)
if err != nil {
golog.Error("Handle","err",err)
return nil, err
}

cmd, ok := ch.CmdMap[param.MsgType]
if ok {
return cmd.Do(ctx.Args)
return cmd.Do(param.Data)
}
return nil, COMMAND_INVALID
}

// 注册命令
func (ch *CommandHandler) Register(cmdType CmdType, cmd Command) {
ch.CmdMap[cmdType] = cmd
func (ch *CommandHandler) Register(CmdType model.CmdType, cmd Command) {
ch.CmdMap[CmdType] = cmd
}


Expand Down
3 changes: 1 addition & 2 deletions endpoint/v1/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,14 @@ package v1
import (
"github.com/gin-gonic/gin"
"github.com/wudaoluo/sonic/common"
"github.com/wudaoluo/sonic/middleware"
"github.com/wudaoluo/sonic/model"
"github.com/wudaoluo/sonic/service"
)

func AuthV1Router(parentRoute gin.IRouter) {
router := parentRoute.Group("/auth")
end := NewAuth()
router.POST("/login",middleware.Jwt(),end.Login)
router.POST("/login",end.Login)
router.POST("/logout",end.Logout)
router.POST("/token/refresh",end.TokenRefresh)
}
Expand Down
36 changes: 19 additions & 17 deletions endpoint/v1/logic.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,40 +4,42 @@ import (
"github.com/gin-gonic/gin"
"github.com/wudaoluo/sonic/common"
"github.com/wudaoluo/sonic/middleware"
"github.com/wudaoluo/sonic/model"
"github.com/wudaoluo/sonic/service"
"github.com/wudaoluo/sonic/queue"
)

func LogicV1Router(parentRoute gin.IRouter) {
router := parentRoute.Group("/auth")
end := NewAuth()
router.POST("/login",middleware.Jwt(),end.Login)
router.POST("/logout",end.Logout)
router.POST("/token/refresh",end.TokenRefresh)
router := parentRoute.Group("/logic")
router.Use(middleware.Jwt())
end := NewLogic()
router.POST("/command",end.Command)
}

type logic struct {
service *service.AuthService
}

func NewLogic() *auth {
return &auth{
service.NewAuthService(),
func NewLogic() *logic {
return &logic{
}
}

//用来模拟的接口
func (l logic) Command(c *gin.Context) {
var req model.AuthLogin
if err := c.Bind(&req); err != nil {
buf,err := c.GetRawData()
if err != nil {
common.GinJsonRespErr(c,common.PARAM_ERROR)
return
}

ret,err := common.Cmd.Handle(&common.CmdContext{CmdType: common.MsgReceive, Args: " Post"})
err = queue.Producer(c,buf)
if err != nil {
common.GinJsonRespErr(c,err)
common.GinJsonRespErr(c,common.SERVICE_ERROR)
return
}
common.GinJsonResp(c,ret)

//ret,err := common.Cmd.Handle(&common.CmdContext{CmdType: common.MsgReceive, Args: " Post"})
//if err != nil {
// common.GinJsonRespErr(c,err)
// return
//}
common.GinJsonResp(c,true)
}

3 changes: 2 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/gin-gonic/gin v1.6.3
github.com/go-sql-driver/mysql v1.5.0
github.com/smartystreets/goconvey v1.6.4
github.com/ivpusic/grpool v1.0.0
github.com/juju/ratelimit v1.0.1
github.com/spf13/cast v1.3.0
github.com/spf13/cobra v1.0.0
github.com/spf13/viper v1.7.0
Expand Down
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,17 @@ github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2p
github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/ivpusic/grpool v1.0.0 h1:+FCiCo3GhfsvzfXuJWnpJUNb/VaqyYVgG8C+qvh07Rc=
github.com/ivpusic/grpool v1.0.0/go.mod h1:WPmiAI5ExAn06vg+0JzyPzXMQutJmpb7TrBtyLJkOHQ=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.9 h1:9yzud/Ht36ygwatGx56VwCZtlI/2AD15T1X2sjSuGns=
github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/juju/ratelimit v1.0.1 h1:+7AIFJVQ0EQgq/K9+0Krm7m530Du7tIz0METWzN0RgY=
github.com/juju/ratelimit v1.0.1/go.mod h1:qapgC/Gy+xNh9UxzV13HGGl/6UXNN+ct+vwSgWNm/qk=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
Expand Down
3 changes: 3 additions & 0 deletions middleware/jwt.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"github.com/wudaoluo/golog"
"github.com/wudaoluo/sonic/common"
"github.com/wudaoluo/sonic/model"
"net/http"
"time"
)
/*
Expand Down Expand Up @@ -61,10 +62,12 @@ func Jwt() gin.HandlerFunc {
user,err := ParseToken(c.GetHeader(TOKEN),false)
if err != nil {
golog.Error("middleware.jwt","func","parseToken","err",err)
c.AbortWithStatus(http.StatusUnauthorized)
return
}
c.Set(UID,user.Uid)
c.Set(USERNAME,user.Username)
c.Next()
}
}

Expand Down
5 changes: 5 additions & 0 deletions model/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ type Config struct {
Default ConfigDefault
Gateway ConfigGateway
Auth ConfigAuth
Logic ConfigLogic
Queue ConfigQueue
Cache ConfigCache
Storage ConfigStorage
Expand All @@ -29,6 +30,10 @@ type ConfigAuthJwt struct {
Key string
}

type ConfigLogic struct {
Addr string
}

type ConfigQueue struct {
Type string `json:"type"`
Addrs []string `json:"addrs"`
Expand Down
33 changes: 33 additions & 0 deletions model/logic.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package model

import "encoding/json"

type CmdType int

func (c CmdType) String() string {
var value string
switch c {
case MsgReceive:
value = "msg_receive"
case MsgSend:
value = "msg_send"
default:
value = "not found"
}
return value
}

const (
MsgReceive CmdType = iota + 1 //消息接受
MsgSend //消息发送
ContactPersonList //联系人列表
MsgTotalUnRead //总未读书
MsgUnRead //消息未读数

)


type LogicCommand struct {
MsgType CmdType `json:"msg_type"`
Data json.RawMessage `json:"data"`
}
3 changes: 1 addition & 2 deletions queue/queue_default/queue_default.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package queue_default

import (
"context"
"github.com/wudaoluo/sonic/model"
"sync/atomic"
"context"
)

type QueueDefault struct {
Expand Down Expand Up @@ -50,6 +50,5 @@ func (q *QueueDefault) Producer(ctx context.Context,buf []byte) error {
if atomic.LoadInt32(&q.status) == 1 {
q.queue <- buf
}

return nil
}
8 changes: 4 additions & 4 deletions service/logic.go → service/logic_command.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package service


import (
"fmt"
"github.com/wudaoluo/sonic/common"
"github.com/wudaoluo/sonic/model"
)



func init() {
common.Cmd.Register(common.MsgReceive, &MsgReceive{})
common.Cmd.Register(model.MsgReceive, &MsgReceive{})
}


Expand All @@ -19,6 +21,4 @@ type MsgReceive struct {
func (m *MsgReceive) Do(args interface{}) (interface{}, error) {
fmt.Println("PostCommand")
return args, nil
}


}
Loading

0 comments on commit 6b9e998

Please sign in to comment.