keer_zu 发表于 2016-11-30 10:45

一起学go语言啦

本帖最后由 keer_zu 于 2016-11-30 11:03 编辑

最近一个项目,需要go语言。
需要一个通信框架,可以并发处理多路链接和消息处理。

@21ic小喇叭 @yyy71cj @dong_abc

学go语言啦{:lol:}


keer_zu 发表于 2016-11-30 10:47

go语言开发速度快,容易学,支持并发
垃圾回收
编译型语言,效率高
语法有脚本语言的特点
适合做服务器开发

就选go语言啦
........

keer_zu 发表于 2016-11-30 10:55

首先在linux下安装go和sublime,其他组合也行,怎么习惯怎么来。网上大堆

如下图:

keer_zu 发表于 2016-11-30 10:59

随便给一个demo,顺便了解一下go的interface概念和struct概念。
当然,所有环境可以很容易在windows环境下搭建。

代码:
package main

import (
        "fmt"
        "message"
        "time"
)

type S struct{ i int }

func (p *S) Get() int{ return p.i }
func (p *S) Put(v int) { p.i = v }

type R struct{ i int }

func (p *R) Get() int{ return p.i }
func (p *R) Put(v int) { p.i = v }

type I interface {
        Get() int
        Put(int)
}

func f(p I) {
        fmt.Println(p.Get())
        p.Put(1)
}

func f1(p I) {
        switch p.(type) {

        case *S:
                fmt.Println("---- *S")
                break
        case *R:
                fmt.Println("---- *R")
                break
        default:
                fmt.Println("---- no thing")
                break
        }
}

var c chan int

func ready(w string, sec int) {
        time.Sleep(time.Duration(sec) * time.Second)
        fmt.Println(w, "is ready!")
        c <- 1
}
func main() {
        da := message.DmcMessageAnalyzer{}
        da.OnNewFrame(nil, nil)
        var s S
        var r R
        s.i = 5
        r.i = 6
        f(&r)
        f(&s)
        f1(&r)
        f1(&s)
        c = make(chan int)
        go ready("Tea", 2)
        go ready("Coffee", 1)
        fmt.Println("I'm waiting, but not too long...")
        //time.Sleep(5 * time.Second)
        f1 := <-c
        fmt.Println("recv f1: ", f1)
        f2 := <-c
        fmt.Println("recv f2: ", f2)
        fmt.Println("bye")
}



keer_zu 发表于 2016-11-30 11:01

上面代码被命名为:xxx.go
这里就叫test.go吧

然后使用go命令:
go build test.go

如果有错会提示,没有错误会得到可执行文件:test(windows下为test.exe)

就这么简单,玩起来吧。{:lol:}

keer_zu 发表于 2016-11-30 11:18

然后可以尝试一个go的“大”项目
首先确保你的环境已经安装好git,
然后使用 go get github.com/xxx 命令得到该项目源代码

比如我要用到一个go的通信库,
go get github.com/pojoin/golis

执行完毕后,在你的go目录下回有这个project的代码,我的在:
/root/go/src/github.com/pojoin/golis 下面。

用到这个库的地方,import进来(比如下面代码):

package main

import (
        "data_manager"
        "fmt"
        "github.com/pojoin/golis"
        "message"
        //        "time"
)

func main() {
        s := golis.NewServer()
        s.FilterChain().AddLast("test", &filter{})
        s.SetCodecer(&echoProtocalCodec{})
        s.RunOnPort("tcp", ":9090")
}

type echoProtocalCodec struct {
        golis.ProtocalCodec
}

type dmc struct {
        data_manager.DmcInfo
}

type stream struct {
        data_manager.StreamInfo
}

type room struct {
        data_manager.RoomInfo
}

type command struct {
        message.Command
}

func (*echoProtocalCodec) Decode(buffer *golis.Buffer, dataCh chan<- interface{}) error {
        //var i int

        //length := buffer.GetWritePos()
        fmt.Println("......Decode... len:", buffer.GetWritePos()-buffer.GetReadPos())
        if buffer.GetWritePos()-buffer.GetReadPos() > 60 {
                fmt.Println("#################\n#######################\n#################\n#############\n")
        }
        /*
                for i = 0; i < length; i = i + 1 {
                        fmt.Println(" ", buffer.GetBufItem(i))
                        if buffer.GetBufItem(i) == 0x00 {
                                bs, _ := buffer.ReadBytes(i)
                                buffer.ResetRead()
                                buffer.ResetWrite()
                                if i < length-1 {
                                        buffer.GetSlice(i+1, length-1)
                                        dataCh <- bs
                                        length = buffer.GetWritePos()
                                        i = 0
                                        continue
                                } else {
                                        dataCh <- bs
                                        break
                                }
                        }
                }*/
        bs, _ := buffer.ReadBytes(buffer.GetWritePos() - buffer.GetReadPos())
        buffer.ResetRead()
        buffer.ResetWrite()
        dataCh <- bs

        return nil
}

type filter struct{}

func (*filter) SessionOpened(session *golis.Iosession) bool {
        fmt.Println("session opened,the client is ", session.Conn().RemoteAddr().String())
        fmt.Println("+ session id: ", session.Id())
        return true
}

func (*filter) SessionClosed(session *golis.Iosession) bool {
        fmt.Println("+ session closed, session id: ", session.Id())
        return true
}

func (*filter) MsgReceived(session *golis.Iosession, msg interface{}) bool {
        ma := message.DmcMessageAnalyzer{}
        if bs, ok := msg.([]byte); ok {
                fmt.Println(".....MsgReceived....")
                ma.OnNewFrame(session, "+++ new frame!!!")
                fmt.Println("+ received msg :", string(bs))
                fmt.Println("+ session id: ", session.Id())
                //if session.Id()%3 == 1 {
                //        fmt.Println("start sleeping...")
                //        time.Sleep(3 * time.Second)
                //        fmt.Println("end sleep.")
                //}
                //replayMsg := fmt.Sprintf("echoServer received msg : %v", string(bs))
                ma.OnNewFrame(session, bs)
                //session.Write([]byte(replayMsg))
        }
        return true
}

func (*filter) MsgSend(session *golis.Iosession, message interface{}) bool {
        fmt.Println("+ send msg, session id: ", session.Id())
        return true
}

func (*filter) ErrorCaught(session *golis.Iosession, err error) bool {
        fmt.Println("+ ErrorCaught, session id: %d", session.Id())
        return true
}


文件起名:golisTest.go

然后进入golisTest.go所在目录,执行:
    go build golisTest.go

编译器会自己在自己的/root/go/src目录下找到所依赖代码,最终生成可执行文件。

baiyunpiapia 发表于 2016-11-30 11:56

这种语言第一次听说哦

keer_zu 发表于 2016-11-30 13:03

yyy71cj 发表于 2016-11-30 11:52
只要有用,语法倒是次要的
一看这风格,很好
多多分享 ...

编程风格是它自己调整的,你随便写,保存的一刹那就给你对齐了。{:lol:}

keer_zu 发表于 2016-11-30 15:06

baiyunpiapia 发表于 2016-11-30 11:56
这种语言第一次听说哦

google出品,今年编程语言排行榜上升最快语言

ddllxxrr 发表于 2016-11-30 18:22

go语言第一次听说,学习了

keer_zu 发表于 2016-11-30 19:07

ddllxxrr 发表于 2016-11-30 18:22
go语言第一次听说,学习了

比较擅长并发和分布式环境。很多云平台的选择

keer_zu 发表于 2016-11-30 20:10

命令部分:

package message

import (
        //"fmt"
        //"container/list"
        "errors"
        "github.com/pojoin/golis"
)

type CommandProperty int

const (
        ProvideResult CommandProperty = iota
        NoProvideResult
)

type Command interface {
        BuildResponse(info interface{}) (string, error)
        CommandHandle(session *golis.Iosession) error
}

type CommandAttribute struct {
        CommandName      string
        MsgId            string
        IsProvidedResult CommandProperty
}

type DmcCommandRegist struct {
        cmdAtt    CommandAttribute
        RoomId    int32
        SessionId int32
}

func (dcr *DmcCommandRegist) BuildResponse(info interface{}) (string, error) {
        return "abc", errors.New("cde")
}

func (dcr *DmcCommandRegist) CommandHandle(session *golis.Iosession) error {
        return errors.New("abc")
}

type CommandPool struct {
        WaitMap map*Command
}

func (cp *CommandPool) Add(cmd *Command, msgId string) {
        cp.WaitMap = cmd
}

type CommandDb struct {
        CommandMap map*Command
}

func (cdb *CommandDb) AddCommand(cmd *Command, cmdName string) {
        cdb.CommandMap = cmd
}

func (cdb *CommandDb) GetCommand(name string) (*Command, error) {

        if cdb.CommandMap != nil {
                return cdb.CommandMap, nil
        }

        err := errors.New("This command is not exist! ")

        return nil, err
}

keer_zu 发表于 2016-12-1 10:27

本帖最后由 keer_zu 于 2016-12-1 10:29 编辑

对上贴中的command和task概念做了区分,放在两个文件里面:
command.go和task.go

分别对CommandDb和TaskPool(上贴中CommandPool)实现了单例模式,保证对象实例的唯一性,使用测试函数做了测试,三个文件代码如下:

command.go:

package message

import (
      "errors"
      "fmt"
      "github.com/pojoin/golis"
      "sync"
)

var once sync.Once

type CommandProperty int

//const (
//      ProvideResult CommandProperty = iota
//      NoProvideResult
//)

type Command interface {
      BuildResponse(info interface{}) (string, error)
      CommandHandle(session *golis.Iosession) error
      GetCommandName() string
      IsProvidedResult() bool
}

type CommandAttribute struct {
      CommandName string
      //MsgId            string
      IsProvidedResult bool //CommandProperty
}

type DmcCommandRegist struct {
      cmdAtt    CommandAttribute
      RoomId    int32
      SessionId int32
}

func (dcr *DmcCommandRegist) BuildResponse(info interface{}) (string, error) {
      return "abc", errors.New("cde")
}

func (dcr *DmcCommandRegist) CommandHandle(session *golis.Iosession) error {
      return errors.New("abc")
}

func (dcr *DmcCommandRegist) GetCommandName() string {
      return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandRegist) IsProvidedResult() bool {
      return dcr.cmdAtt.IsProvidedResult
}

type CommandDb struct {
      CommandMap map*Command
}

var commandDbInstance *CommandDb

func GetCommandDbInstance() *CommandDb {
      once.Do(func() {
                fmt.Println("+++++++++++ commandDb instance +++++++")
                commandDbInstance = &CommandDb{}
      })
      return commandDbInstance
}

func (cdb *CommandDb) AddCommand(cmd *Command, cmdName string) {
      cdb.CommandMap = cmd
}

func (cdb *CommandDb) GetCommand(name string) (*Command, error) {

      if cdb.CommandMap != nil {
                return cdb.CommandMap, nil
      }

      err := errors.New("This command is not exist!")

      return nil, err
}




task.go:
package message

import (
      "fmt"
      //      "errors"
      //      "github.com/pojoin/golis"
      "sync"
)

var taskPoolOnce sync.Once

type TaskInfo struct {
      Cmd   *Command
      MsgId string
}

type TaskPool struct {
      WaitMap map*TaskInfo
}

var taskPoolInstance *TaskPool

func GetTaskPoolInstance() *TaskPool {
      taskPoolOnce.Do(func() {
                fmt.Println("+++++++++++ taskPool instance +++++++")
                taskPoolInstance = &TaskPool{}
      })
      return taskPoolInstance
}

func (tp *TaskPool) Add(task *TaskInfo, msgId string) {
      tp.WaitMap = task
}

func (tp *TaskPool) Del(msgId string) {
      delete(tp.WaitMap, msgId)
}


测试函数:
package main

import (
      "fmt"
      "message"
)

func main() {
      fmt.Println("message test")
      var cmddb1, cmddb2, cmddb3 *message.CommandDb
      cmddb1 = message.GetCommandDbInstance()
      s1 := fmt.Sprintf(" %d", cmddb1)
      fmt.Println("cmddb1: ", s1)
      cmddb2 = message.GetCommandDbInstance()
      s2 := fmt.Sprintf(" %d", cmddb2)
      fmt.Println("cmddb2: ", s2)
      cmddb3 = message.GetCommandDbInstance()
      s3 := fmt.Sprintf(" %d", cmddb3)
      fmt.Println("cmddb3: ", s3)

      var taskp1, taskp2, taskp3 *message.TaskPool
      taskp1 = message.GetTaskPoolInstance()
      t1 := fmt.Sprintf(" %d", taskp1)
      fmt.Println("taskp1: ", t1)
      taskp2 = message.GetTaskPoolInstance()
      t2 := fmt.Sprintf(" %d", taskp2)
      fmt.Println("taskp2: ", t2)
      taskp3 = message.GetTaskPoolInstance()
      t3 := fmt.Sprintf(" %d", taskp3)
      fmt.Println("taskp3: ", t3)
}



@yyy71cj @21ic小喇叭 @dong_abc @ayb_ice @Simon21ic



keer_zu 发表于 2016-12-2 20:03

package message

import (
        "container/list"
        "data_manager"
        "encoding/json"
        "errors"
        "fmt"
        "sync"

        "github.com/pojoin/golis"
)

var once sync.Once

type CommandProperty int

type Command interface {
        BuildResponse(info interface{}) (string, error)
        CommandHandle(session *golis.Iosession, CmdInfo interface{}) error
        GetCommandName() string
        IsProvidedResult() bool
}

type CommandAttribute struct {
        CommandName      string
        IsProvidedResult bool //CommandProperty
}

////////////////////////////dmccommand ////////////////////////////
////////////////////// dmc_register/////////////////////
type DmcRegist struct {
        Command string `json:"command"`
        MsgId   string `json:"msg_id"`
        RoomIdint32`json:"room_id"`
}

type DmcCommandRegist struct {
        cmdAtt CommandAttribute
}

//////////////////////dmc_heart_beat//////////////////
type DmcHeartBeat struct {
        Command string `json:"command"`
        MsgId   string `json:"msg_id"`
        DmcId   int32`json:"dmc_id"`
}

type DmcCommandHeartBeat struct {
        cmdAtt CommandAttribute
}

////////////////////// dmc_unregister //////////////////

type DmcUnregister struct {
        Command string `json:"command"`
        MsgId   string `json:"msg_id"`
        DmcId   int32`json:"dmc_id"`
}

type DmcCommandUnregister struct {
        cmdAtt CommandAttribute
}

////////////////////// dmc_stream_query //////////////////
type DmcStreamQuery struct {
        Command    string `json:"command"`
        MsgId      string `json:"msg_id"`
        DmcId      int32`json:"dmc_id"`
        StreamName string `json:"stream_name"`
}

type DmcCommandStreamQuery struct {
        cmdAtt CommandAttribute
}

////////////////// dmc _all_stream_update ////////////////
type DmcAllStreamUpdate struct {
        Command      string                        `json:"command"`
        MsgId          string                        `json:"msg_id"`
        DmcId          int32                           `json:"dmc_id"`
        StreamInfoList []data_manager.StreamAttributes `json:"stream_info"`
}

type DmcCommandAllStreamUpdate struct {
        cmdAtt CommandAttribute
}

////////////////// dmc _capability_update ////////////////
type DmcCapabilityUpdate struct {
        Command string            `json:"command"`
        MsgId   string            `json:"msg_id"`
        DmcId   int32             `json:"dmc_id"`
        Cap   Capability      `json:"capability"`
        NCap    NetworkCapability `json:"network_capability"`
        Ld      Load            `json:"load"`
        NLd   NetworkLoad       `json:"network_load"`
}

type DmcCommandCapabilityUpdate struct {
        cmdAtt CommandAttribute
}

//////////////////// dmc _stream_ update ////////////////
type DmcStreamUpdate struct {
        Command string `json:"command"`
        MsgId   string `json:"msg_id"`
        DmcId   int32`json:"dmc_id"`
        ////////////////// StreamAttributes /////////////////
        Name       string                     `json:"stream_name"`
        Operate    data_manager.StreamOperate   `json:"operate"`
        Status   data_manager.StreamState   `json:"status"`
        Attributes data_manager.StreamAttribute `json:"attributes"`
        Type       data_manager.StreamType      `json:"type"`
        DmsInfo    []string                     `json:"dms_info"`
}

type DmcCommandStreamUpdate struct {
        cmdAtt CommandAttribute
}

//////////////////// dmc_get_dms_request ////////////////
type DmcGetDmsRequest struct {
        Command string `json:"command"`
        MsgId   string `json:"msg_id"`
        DmcId   int32`json:"dmc_id"`
}

type DmcCommandGetDmsRequest struct {
        cmdAtt CommandAttribute
}

//////////////////////////////////////////////////////////////////

//////////////////////////   gmc request & response   /////////////////////////////

type GmcRegResponse struct {
        Command string `json:"command"`
        MsgId   string `json:"msg_id"`
        DmcId   int32`json:"dmc_id"`
}

type GmcResponse struct {
        Command string `json:"command"`
        MsgId   string `json:"msg_id"`
}

type GmcStreamQueryResult struct {
        Command    string   `json:"command"`
        MsgId      string   `json:"msg_id"`
        Result   string   `json:"result"`
        StreamName string   `json:"stream_name"`
        DmsInfo    *list.List `json:"dms_info"`
}

///////////////////////////////////////////////////////////////////////////////////

func (dcr *DmcCommandRegist) BuildResponse(info interface{}) (string, error) {

        return "abc", errors.New("cde")
}

func (dcr *DmcCommandRegist) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
        fmt.Println("register command handle ........ ")
        cmd := CmdInfo.(*DmcRegist)
        fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " roomid:", cmd.RoomId)
        dmc_instance := data_manager.GetDmcInstance()
        dmc_id := dmc_instance.GetDmcId()
        dmc_info := data_manager.DmcInfo{dmc_id, list.New(), list.New(), cmd.RoomId}
        dmc_instance.AddDmcInfo(dmc_id, dmc_info)
        gmcResponse := &GmcRegResponse{"gmc_reg_response", cmd.MsgId, dmc_id}

        b, err := json.Marshal(gmcResponse)
        if err != nil {
                fmt.Println("encoding faild")
                return errors.New("encoding faild")
        } else {
                fmt.Println("encoded data : ")
                //fmt.Println(b)
                fmt.Println(string(b))
        }

        buf := make([]byte, len(b)+1)
        copy(buf, b[:])
        buf = 0x00

        fmt.Println("------------- Session write frame: ---")

        session.Write(buf)

        return nil
}

func (dcr *DmcCommandRegist) GetCommandName() string {
        return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandRegist) IsProvidedResult() bool {
        return dcr.cmdAtt.IsProvidedResult
}

///////////////////// dmc_heart_beat ////////////////////////

func (dcr *DmcCommandHeartBeat) BuildResponse(info interface{}) (string, error) {

        return "abc", errors.New("cde")
}

func (dcr *DmcCommandHeartBeat) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
        fmt.Println("heart beat command handle ........ ")
        return nil
}

func (dcr *DmcCommandHeartBeat) GetCommandName() string {
        return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandHeartBeat) IsProvidedResult() bool {
        return dcr.cmdAtt.IsProvidedResult
}

////////////////////// dmc_unregister //////////////////
func (dcr *DmcCommandUnregister) BuildResponse(info interface{}) (string, error) {

        return "abc", errors.New("cde")
}

func (dcr *DmcCommandUnregister) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
        fmt.Println("unregister command handle ........ ")
        cmd := CmdInfo.(*DmcUnregister)
        fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " dmcid:", cmd.DmcId)
        dmc_instance := data_manager.GetDmcInstance()

        dmc_instance.DelDmcInfo(cmd.DmcId)
        gmcResponse := &GmcResponse{"gmc_response", cmd.MsgId}

        b, err := json.Marshal(gmcResponse)
        if err != nil {
                fmt.Println("encoding faild")
                return errors.New("encoding faild")
        } else {
                fmt.Println("encoded data : ")
                //fmt.Println(b)
                fmt.Println(string(b))
        }

        buf := make([]byte, len(b)+1)
        copy(buf, b[:])
        buf = 0x00

        fmt.Println("------------- Session write frame: ---")

        session.Write(buf)
        return nil
}

func (dcr *DmcCommandUnregister) GetCommandName() string {
        return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandUnregister) IsProvidedResult() bool {
        return dcr.cmdAtt.IsProvidedResult
}

////////////////////// dmc_stream_query //////////////////
func (dcr *DmcCommandStreamQuery) BuildResponse(info interface{}) (string, error) {

        return "abc", errors.New("cde")
}

func (dcr *DmcCommandStreamQuery) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
        fmt.Println("stream query command handle ........ ")
        cmd := CmdInfo.(*DmcStreamQuery)
        fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " dmcid:", cmd.DmcId, "streamname:", cmd.StreamName)
        stream_instance := data_manager.GetStreamInstance()
        stream_info, result := stream_instance.GetStreamInfo(cmd.StreamName)
        var queryresponse *GmcStreamQueryResult
        if result == true {
                queryresponse = &GmcStreamQueryResult{"gmc_stream_query_result", cmd.MsgId, "Found", cmd.StreamName, stream_info.DmsInfo}
        } else {
                queryresponse = &GmcStreamQueryResult{"gmc_stream_query_result", cmd.MsgId, "Not Found", cmd.StreamName, nil}
        }

        b, err := json.Marshal(queryresponse)
        if err != nil {
                fmt.Println("encoding faild")
                return errors.New("encoding faild")
        } else {
                fmt.Println("encoded data : ")
                //fmt.Println(b)
                fmt.Println(string(b))
        }

        buf := make([]byte, len(b)+1)
        copy(buf, b[:])
        buf = 0x00

        fmt.Println("------------- Session write frame: ---")

        session.Write(buf)
        return nil
}

func (dcr *DmcCommandStreamQuery) GetCommandName() string {
        return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandStreamQuery) IsProvidedResult() bool {
        return dcr.cmdAtt.IsProvidedResult
}

////////////////// dmc_all_stream_update ////////////////
func (dcr *DmcCommandAllStreamUpdate) BuildResponse(info interface{}) (string, error) {

        return "abc", errors.New("cde")
}

func (dcr *DmcCommandAllStreamUpdate) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
        fmt.Println("all streamupdate command handle ........ ")
        cmd := CmdInfo.(*DmcAllStreamUpdate)
        fmt.Printf("------------------ len=%d cap=%d slice=%v\n", len(cmd.StreamInfoList), cap(cmd.StreamInfoList), cmd.StreamInfoList)

        return nil
}

func (dcr *DmcCommandAllStreamUpdate) GetCommandName() string {
        return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandAllStreamUpdate) IsProvidedResult() bool {
        return dcr.cmdAtt.IsProvidedResult
}

////////////////// dmc_capability_update ////////////////
func (dcr *DmcCommandCapabilityUpdate) BuildResponse(info interface{}) (string, error) {

        return "abc", errors.New("cde")
}

func (dcr *DmcCommandCapabilityUpdate) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
        fmt.Println("capabilityupdate command handle ........ ")
        return nil
}

func (dcr *DmcCommandCapabilityUpdate) GetCommandName() string {
        return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandCapabilityUpdate) IsProvidedResult() bool {
        return dcr.cmdAtt.IsProvidedResult
}

//////////////////// dmc_stream_update ////////////////
func (dcr *DmcCommandStreamUpdate) BuildResponse(info interface{}) (string, error) {

        return "abc", errors.New("cde")
}

func (dcr *DmcCommandStreamUpdate) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
        fmt.Println("streamupdate command handle ........ ")
        return nil
}

func (dcr *DmcCommandStreamUpdate) GetCommandName() string {
        return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandStreamUpdate) IsProvidedResult() bool {
        return dcr.cmdAtt.IsProvidedResult
}

//////////////////// dmc_get_dms_request ////////////////
func (dcr *DmcCommandGetDmsRequest) BuildResponse(info interface{}) (string, error) {

        return "abc", errors.New("cde")
}

func (dcr *DmcCommandGetDmsRequest) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
        fmt.Println("get dms request command handle ........ ")
        return nil
}

func (dcr *DmcCommandGetDmsRequest) GetCommandName() string {
        return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandGetDmsRequest) IsProvidedResult() bool {
        return dcr.cmdAtt.IsProvidedResult
}

////////////////////////////////////////////////// CommandDb /////////////////////////////////////////////////////////
type CommandDb struct {
        CommandMapmapCommand
        JsonReflect *JsonReflectMap
}

var commandDbInstance *CommandDb

func GetCommandDbInstance() *CommandDb {
        once.Do(func() {
                commandDbInstance = &CommandDb{}
                commandDbInstance.CommandMap = make(mapCommand)
                commandDbInstance.JsonReflect = Json()
                //////////////////////////////////////// add command /////////////////////////////////////////

                /////////////////////////////////////// dmc_register /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_register", DmcRegist{})
                commandDbInstance.AddCommand(&DmcCommandRegist{cmdAtt: CommandAttribute{CommandName: "dmc_register", IsProvidedResult: false}}, "dmc_register")

                ///////////////////////////////////// dmc_heart_beat /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_heart_beat", DmcHeartBeat{})
                commandDbInstance.AddCommand(&DmcCommandHeartBeat{cmdAtt: CommandAttribute{CommandName: "dmc_heart_beat", IsProvidedResult: false}}, "dmc_heart_beat")

                ///////////////////////////////////// dmc_unregister /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_unregister", DmcUnregister{})
                commandDbInstance.AddCommand(&DmcCommandUnregister{cmdAtt: CommandAttribute{CommandName: "dmc_unregister", IsProvidedResult: false}}, "dmc_unregister")

                ///////////////////////////////////// dmc_stream_query /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_stream_query", DmcStreamQuery{})
                commandDbInstance.AddCommand(&DmcCommandStreamQuery{cmdAtt: CommandAttribute{CommandName: "dmc_stream_query", IsProvidedResult: false}}, "dmc_stream_query")

                ///////////////////////////////////// dmc_all_stream_update /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_all_stream_update", DmcAllStreamUpdate{})
                commandDbInstance.AddCommand(&DmcCommandAllStreamUpdate{cmdAtt: CommandAttribute{CommandName: "dmc_all_stream_update", IsProvidedResult: false}}, "dmc_all_stream_update")

                ///////////////////////////////////// dmc_capability_update /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_capability_update", DmcCapabilityUpdate{})
                commandDbInstance.AddCommand(&DmcCommandCapabilityUpdate{cmdAtt: CommandAttribute{CommandName: "dmc_capability_update", IsProvidedResult: false}}, "dmc_capability_update")

                ///////////////////////////////////// dmc_stream_update /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_stream_update", DmcStreamUpdate{})
                commandDbInstance.AddCommand(&DmcCommandStreamUpdate{cmdAtt: CommandAttribute{CommandName: "dmc_stream_update", IsProvidedResult: false}}, "dmc_stream_update")

                ///////////////////////////////////// dmc_get_dms_request /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_get_dms_request", DmcGetDmsRequest{})
                commandDbInstance.AddCommand(&DmcCommandGetDmsRequest{cmdAtt: CommandAttribute{CommandName: "dmc_get_dms_request", IsProvidedResult: true}}, "dmc_get_dms_request")

        })
        return commandDbInstance
}

func (cdb *CommandDb) AddCommand(cmd Command, cmdName string) {
        cdb.CommandMap = cmd
}

func (cdb *CommandDb) GetCommand(name string) (Command, error) {

        if cdb.CommandMap != nil {
                return cdb.CommandMap, nil
        }

        err := errors.New("This command is not exist!")

        return nil, err
}


dong_abc 发表于 2016-12-3 16:40

其实go语言应用很普遍。

dong_abc 发表于 2016-12-4 00:01

我觉得楼主没必要在这里讨论这个,你想把梳子卖给和尚,这很励志,但没什么意义!

keer_zu 发表于 2016-12-5 08:23

dong_abc 发表于 2016-12-4 00:01
我觉得楼主没必要在这里讨论这个,你想把梳子卖给和尚,这很励志,但没什么意义! ...

{:titter:}

keer_zu 发表于 2016-12-5 08:23

dong_abc 发表于 2016-12-3 16:40
其实go语言应用很普遍。

是的

keer_zu 发表于 2016-12-5 16:05

继续完善command.go
Part 1:

package message

import (
      "container/list"
      "data_manager"
      "encoding/json"
      "errors"
      "fmt"
      "sync"

      "github.com/pojoin/golis"
)

var once sync.Once

type CommandProperty int

type Command interface {
      //BuildResponse(info interface{}) (string, error)
      CommandHandle(session *golis.Iosession, CmdInfo interface{}) error
      GetCommandName() string
      IsProvidedResult() bool
}

type CommandAttribute struct {
      CommandName      string
      IsProvidedResult bool //CommandProperty
}

////////////////////////////dmccommand ////////////////////////////
////////////////////// dmc_register/////////////////////
type DmcRegist struct {
      Command string `json:"command"`
      MsgId   string `json:"msg_id"`
      RoomIdint32`json:"room_id"`
}

type DmcCommandRegist struct {
      cmdAtt CommandAttribute
}

//////////////////////dmc_heart_beat//////////////////
type DmcHeartBeat struct {
      Command string `json:"command"`
      MsgId   string `json:"msg_id"`
      DmcId   int32`json:"dmc_id"`
}

type DmcCommandHeartBeat struct {
      cmdAtt CommandAttribute
}

////////////////////// dmc_unregister //////////////////

type DmcUnregister struct {
      Command string `json:"command"`
      MsgId   string `json:"msg_id"`
      DmcId   int32`json:"dmc_id"`
}

type DmcCommandUnregister struct {
      cmdAtt CommandAttribute
}

////////////////////// dmc_stream_query //////////////////
type DmcStreamQuery struct {
      Command    string `json:"command"`
      MsgId      string `json:"msg_id"`
      DmcId      int32`json:"dmc_id"`
      StreamName string `json:"stream_name"`
}

type DmcCommandStreamQuery struct {
      cmdAtt CommandAttribute
}

////////////////// dmc _all_stream_update ////////////////
type DmcAllStreamUpdate struct {
      Command      string                        `json:"command"`
      MsgId          string                        `json:"msg_id"`
      DmcId          int32                           `json:"dmc_id"`
      StreamInfoList []data_manager.StreamAttributes `json:"stream_info"`
}

type DmcCommandAllStreamUpdate struct {
      cmdAtt CommandAttribute
}

////////////////// dmc _capability_update ////////////////
type DmcCapabilityUpdate struct {
      Command string            `json:"command"`
      MsgId   string            `json:"msg_id"`
      DmcId   int32             `json:"dmc_id"`
      Cap   Capability      `json:"capability"`
      NCap    NetworkCapability `json:"network_capability"`
      Ld      Load            `json:"load"`
      NLd   NetworkLoad       `json:"network_load"`
}

type DmcCommandCapabilityUpdate struct {
      cmdAtt CommandAttribute
}

//////////////////// dmc _stream_ update ////////////////
type DmcStreamUpdate struct {
      Command string `json:"command"`
      MsgId   string `json:"msg_id"`
      DmcId   int32`json:"dmc_id"`
      ////////////////// StreamAttributes /////////////////
      Operate    data_manager.StreamOperate   `json:"operate"`
      Name       string                     `json:"stream_name"`
      Status   data_manager.StreamState   `json:"status"`
      Attributes data_manager.StreamAttribute `json:"attributes"`
      Type       data_manager.StreamType      `json:"type"`
      DmsInfo    []string                     `json:"dms_info"`
}

type DmcCommandStreamUpdate struct {
      cmdAtt CommandAttribute
}

//////////////////// dmc_get_dms_request ////////////////
type DmcGetDmsRequest struct {
      Command string                  `json:"command"`
      MsgId   string                  `json:"msg_id"`
      DmcId   int32                   `json:"dmc_id"`
      Type    data_manager.StreamType `json:"type"`
}

type DmcCommandGetDmsRequest struct {
      cmdAtt CommandAttribute
}

////////// dmc_get_dms_response /////////////
type DmcGetDmsResponse struct {
      Command string   `json:"command"`
      MsgId   string   `json:"msg_id"`
      DmcId   int32    `json:"dmc_id"`
      DmsInfo []string `json:"dms_info"`
}

type DmcCommandGetDmsResponse struct {
      cmdAtt CommandAttribute
}

//////////////////////////////////////////////////////////////////

//////////////////////////   gmc request & response   /////////////////////////////

func AddFrameTail(input []byte) []byte {
      buf := make([]byte, len(input)+1)
      copy(buf, input[:])
      buf = 0x00

      return buf
}

func JsonMarshal(msgStruct interface{}) ([]byte, error) {
      b, err := json.Marshal(msgStruct)
      if err != nil {
                fmt.Println("encoding faild")
                return nil, errors.New("encoding faild")
      } else {
                fmt.Println("encoded data : ")
                //fmt.Println(b)
                fmt.Println(string(b))
      }

      return b, err
}

type GmcMessage interface {
      BuildMessage() ([]byte, error)
}

/////// gmc_reg_response ///////
type GmcRegResponse struct {
      Command string `json:"command"`
      MsgId   string `json:"msg_id"`
      DmcId   int32`json:"dmc_id"`
}

func (gm *GmcRegResponse) BuildMessage() ([]byte, error) {

      //gmcRegResponse := &GmcRegResponse{"gmc_reg_response", gm.MsgId, gm.DmcId}

      b, err := JsonMarshal(*gm)
      if b == nil {
                return b, err

      }

      buf := AddFrameTail(b)

      return buf, nil
}

/////// gmc_response ///////
type GmcResponse struct {
      Command string `json:"command"`
      MsgId   string `json:"msg_id"`
}

func (gm *GmcResponse) BuildMessage() ([]byte, error) {
      //gmcResponse := &GmcResponse{"gmc_response", gm.MsgId}

      b, err := JsonMarshal(*gm)
      if b == nil {
                return b, err

      }

      buf := AddFrameTail(b)

      return buf, nil
}

/////// gmc_stream_query_result ///////

type GmcStreamQueryResult struct {
      Command    string   `json:"command"`
      MsgId      string   `json:"msg_id"`
      Result   string   `json:"result"`
      StreamName string   `json:"stream_name"`
      DmsInfo    *list.List `json:"dms_info"`
}

func (gm *GmcStreamQueryResult) BuildMessage() ([]byte, error) {

      b, err := JsonMarshal(*gm)
      if b == nil {
                return b, err

      }

      buf := AddFrameTail(b)

      return buf, nil
}

//////// gmc_get_dms_request //////////

type GmcGetDmsRequest struct {
      Command string `json:"command"`
      MsgId   string `json:"msg_id"`
}

func (gm *GmcGetDmsRequest) BuildMessage() ([]byte, error) {
      //gmcResponse := &GmcGetDmsRequest{"gmc_get_dms_request", gm.MsgId}

      b, err := JsonMarshal(*gm)
      if b == nil {
                return b, err

      }

      buf := AddFrameTail(b)

      return buf, nil
}

/////////// gmc_get_dms_response /////////
type GmcGetDmsResponse struct {
      Command string   `json:"command"`
      MsgId   string   `json:"msg_id"`
      DmcId   int32    `json:"dmc_id"`
      DmsInfo []string `json:"dms_info"`
}

func (gm *GmcGetDmsResponse) BuildMessage() ([]byte, error) {

      b, err := JsonMarshal(*gm)
      if b == nil {
                return b, err

      }

      buf := AddFrameTail(b)

      return buf, nil
}

/////// gmc_stream_published_notify //////

type GmcStreamPublishedNotify struct {
      Command    string   `json:"command"`
      MsgId      string   `json:"msg_id"`
      StreamName string   `json:"stream_name"`
      DmsInfo    []string `json:"dms_info"`
}

func (gm *GmcStreamPublishedNotify) BuildMessage() ([]byte, error) {

      b, err := JsonMarshal(*gm)
      if b == nil {
                return b, err

      }

      buf := AddFrameTail(b)

      return buf, nil
}

/////////// func BuildGmcMessage ////////////
func BuildGmcMessage(gmcMsg GmcMessage) ([]byte, error) {

      msg, err := gmcMsg.BuildMessage()
      if err != nil {
                return nil, err
      }
      return msg, nil
}

///////////////////////////////////////////////////////////////////////////////////

func (dcr *DmcCommandRegist) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
      fmt.Println("register command handle ........ ")
      cmd := CmdInfo.(*DmcRegist)

      fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " roomid:", cmd.RoomId)
      dmc_instance := data_manager.GetDmcInstance()
      dmc_id := dmc_instance.GetDmcId()

      dmc_info := data_manager.DmcInfo{dmc_id, list.New(), list.New(), cmd.RoomId, session}
      dmc_instance.AddDmcInfo(dmc_id, dmc_info)

      gmcResponse := &GmcRegResponse{"gmc_reg_response", cmd.MsgId, dmc_id}

      buf, err := BuildGmcMessage(gmcResponse)
      if err != nil {
                return err
      }
      fmt.Println("------------- Session write frame: ---")

      session.Write(buf)

      return nil
}

func (dcr *DmcCommandRegist) GetCommandName() string {
      return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandRegist) IsProvidedResult() bool {
      return dcr.cmdAtt.IsProvidedResult
}

///////////////////// dmc_heart_beat ////////////////////////

func (dcr *DmcCommandHeartBeat) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
      fmt.Println("heart beat command handle ........ ")
      cmd := CmdInfo.(*DmcHeartBeat)
      fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " dmcid:", cmd.DmcId)

      return nil
}

func (dcr *DmcCommandHeartBeat) GetCommandName() string {
      return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandHeartBeat) IsProvidedResult() bool {
      return dcr.cmdAtt.IsProvidedResult
}

////////////////////// dmc_unregister //////////////////

func (dcr *DmcCommandUnregister) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
      fmt.Println("unregister command handle ........ ")
      cmd := CmdInfo.(*DmcUnregister)
      fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " dmcid:", cmd.DmcId)
      dmc_instance := data_manager.GetDmcInstance()

      dmc_instance.DelDmcInfo(cmd.DmcId)
      gmcResponse := &GmcResponse{"gmc_response", cmd.MsgId}

      buf, err := BuildGmcMessage(gmcResponse)
      if err != nil {
                return err
      }
      fmt.Println("------------- Session write frame: ---")

      session.Write(buf)
      return nil
}

func (dcr *DmcCommandUnregister) GetCommandName() string {
      return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandUnregister) IsProvidedResult() bool {
      return dcr.cmdAtt.IsProvidedResult
}

////////////////////// dmc_stream_query //////////////////

func (dcr *DmcCommandStreamQuery) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
      fmt.Println("stream query command handle ........ ")
      cmd := CmdInfo.(*DmcStreamQuery)
      fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " dmcid:", cmd.DmcId, "streamname:", cmd.StreamName)
      stream_instance := data_manager.GetStreamInstance()
      stream_info, result := stream_instance.GetStreamInfo(cmd.StreamName)
      var queryresponse *GmcStreamQueryResult
      if result == true {
                queryresponse = &GmcStreamQueryResult{"gmc_stream_query_result", cmd.MsgId, "Found", cmd.StreamName, stream_info.DmsInfo}
      } else {
                queryresponse = &GmcStreamQueryResult{"gmc_stream_query_result", cmd.MsgId, "Not Found", cmd.StreamName, nil}
      }

      b, err := json.Marshal(queryresponse)
      if err != nil {
                fmt.Println("encoding faild")
                return errors.New("encoding faild")
      } else {
                fmt.Println("encoded data : ")
                //fmt.Println(b)
                fmt.Println(string(b))
      }

      buf := make([]byte, len(b)+1)
      copy(buf, b[:])
      buf = 0x00

      fmt.Println("------------- Session write frame: ---")

      session.Write(buf)
      return nil
}

func (dcr *DmcCommandStreamQuery) GetCommandName() string {
      return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandStreamQuery) IsProvidedResult() bool {
      return dcr.cmdAtt.IsProvidedResult
}

////////////////// dmc_all_stream_update ////////////////

func (dcr *DmcCommandAllStreamUpdate) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
      fmt.Println("all streamupdate command handle ........ ")
      cmd := CmdInfo.(*DmcAllStreamUpdate)
      fmt.Printf("------------------ len=%d cap=%d slice=%v\n", len(cmd.StreamInfoList), cap(cmd.StreamInfoList), cmd.StreamInfoList)
      fmt.Println("cmd:", cmd.Command, " dmc id:", cmd.DmcId, " msg id:", cmd.MsgId)
      stream_instance := data_manager.GetStreamInstance()
      stream_lst := cmd.StreamInfoList
      for _, stream_info := range stream_lst {
                temp_stream_info := data_manager.NewStreamInfo(stream_info.Name, cmd.DmcId, stream_info.State, stream_info.Attributes, stream_info.Type, list.New())
                stream_instance.AddStreamInfo(stream_info.Name, temp_stream_info)
      }

      gmcResponse := &GmcResponse{"gmc_response", cmd.MsgId}

      buf, err := BuildGmcMessage(gmcResponse)
      if err != nil {
                return err
      }
      fmt.Println("------------- Session write frame: ---")

      session.Write(buf)
      return nil
}

func (dcr *DmcCommandAllStreamUpdate) GetCommandName() string {
      return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandAllStreamUpdate) IsProvidedResult() bool {
      return dcr.cmdAtt.IsProvidedResult
}

////////////////// dmc_capability_update ////////////////

func (dcr *DmcCommandCapabilityUpdate) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
      fmt.Println("capabilityupdate command handle ........ ")
      cmd := CmdInfo.(*DmcCapabilityUpdate)
      fmt.Println("cmd:", cmd.Command, " msgid:", cmd.MsgId, " dmcid:", cmd.DmcId, " cap item:", cmd.Cap.Item, " ld item", cmd.Ld.Item, " nld item:", cmd.NLd.Item)

      return nil
}

func (dcr *DmcCommandCapabilityUpdate) GetCommandName() string {
      return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandCapabilityUpdate) IsProvidedResult() bool {
      return dcr.cmdAtt.IsProvidedResult
}

//////////////////// dmc_stream_update ////////////////

func (dcr *DmcCommandStreamUpdate) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
      fmt.Println("streamupdate command handle ........ ")
      cmd := CmdInfo.(*DmcStreamUpdate)
      fmt.Println(" cmd:", cmd.Command, " dmc id:", cmd.DmcId, " msg id:", cmd.MsgId, " stream name:", cmd.Name)
      stream_instance := data_manager.GetStreamInstance()
      if cmd.Operate == data_manager.ADDStream {
                temp_stream_info := data_manager.NewStreamInfo(cmd.Name, cmd.DmcId, cmd.Status, cmd.Attributes, cmd.Type, list.New())
                stream_instance.AddStreamInfo(cmd.Name, temp_stream_info)
      } else if cmd.Operate == data_manager.DELStream {
                stream_instance.DelStreamInfo(cmd.Name)

      } else {
                temp_stream_info := data_manager.NewStreamInfo(cmd.Name, cmd.DmcId, cmd.Status, cmd.Attributes, cmd.Type, list.New())
                stream_instance.ModStreamInfo(cmd.Name, temp_stream_info)
      }

      gmcResponse := &GmcResponse{"gmc_response", cmd.MsgId}

      buf, err := BuildGmcMessage(gmcResponse)
      if err != nil {
                return err
      }
      fmt.Println("------------- Session write frame: ---")

      session.Write(buf)

      return nil
}

func (dcr *DmcCommandStreamUpdate) GetCommandName() string {
      return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandStreamUpdate) IsProvidedResult() bool {
      return dcr.cmdAtt.IsProvidedResult
}

//////////////////// dmc_get_dms_request ////////////////

func (dcr *DmcCommandGetDmsRequest) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
      fmt.Println("get dms request command handle ........ ")
      cmd := CmdInfo.(*DmcGetDmsRequest)
      fmt.Println(" cmd:", cmd.Command, " msg id:", cmd.MsgId, " dmc id:", cmd.DmcId)

      dmcManager := data_manager.GetDmcInstance()
      dmc, err1 := dmcManager.GetDmc(data_manager.GET_A_USEFUL_DMS)
      if err1 != nil {
                return errors.New("source dmc session is nil")
      }

      session_source_dmc := dmc.Session

      gmcGetDmsRequest := &GmcGetDmsRequest{"gmc_get_dms_request", cmd.MsgId}
      buf, err := BuildGmcMessage(gmcGetDmsRequest)
      if err != nil {
                return err
      }
      fmt.Println("------------- Session write gmcGetDmsRequest frame: ---")

      session_source_dmc.Write(buf)

      return nil
}

func (dcr *DmcCommandGetDmsRequest) GetCommandName() string {
      return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandGetDmsRequest) IsProvidedResult() bool {
      return dcr.cmdAtt.IsProvidedResult
}


keer_zu 发表于 2016-12-5 16:06

继续完善 command.go

Part 2:
////////// dmc_get_dms_response /////////////

func (dcr *DmcCommandGetDmsResponse) CommandHandle(session *golis.Iosession, CmdInfo interface{}) error {
        fmt.Println("get DmcGetDmsResponsecommand handle ........ ")
        cmd := CmdInfo.(*DmcGetDmsResponse)
        fmt.Println(" cmd:", cmd.Command, " msg id:", cmd.MsgId, " dmc id:", cmd.DmcId)

        taskPool := GetTaskPoolInstance()

        defer taskPool.Del(cmd.MsgId)

        taskInfo, ok := taskPool.GetTaskInfo(cmd.MsgId)
        if !ok {
                return errors.New("can not fand this task!")
        }

        gmcGetDmsReponse := &GmcGetDmsResponse{"gmc_get_dms_response", cmd.MsgId, cmd.DmcId, cmd.DmsInfo}
        buf, err := BuildGmcMessage(gmcGetDmsReponse)
        if err != nil {
                return err
        }
        fmt.Println("------------- Session write GmcGetDmsResponse frame: ---")

        session_dms_request := taskInfo.Session
        session_dms_request.Write(buf)

        return nil
}

func (dcr *DmcCommandGetDmsResponse) GetCommandName() string {
        return dcr.cmdAtt.CommandName
}

func (dcr *DmcCommandGetDmsResponse) IsProvidedResult() bool {
        return dcr.cmdAtt.IsProvidedResult
}

////////////////////////////////////////////////// CommandDb /////////////////////////////////////////////////////////
type CommandDb struct {
        CommandMapmapCommand
        JsonReflect *JsonReflectMap
}

var commandDbInstance *CommandDb

func GetCommandDbInstance() *CommandDb {
        once.Do(func() {
                commandDbInstance = &CommandDb{}
                commandDbInstance.CommandMap = make(mapCommand)
                commandDbInstance.JsonReflect = Json()
                //////////////////////////////////////// add command /////////////////////////////////////////

                /////////////////////////////////////// dmc_register /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_register", DmcRegist{})
                commandDbInstance.AddCommand(&DmcCommandRegist{cmdAtt: CommandAttribute{CommandName: "dmc_register", IsProvidedResult: false}}, "dmc_register")

                ///////////////////////////////////// dmc_heart_beat /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_heart_beat", DmcHeartBeat{})
                commandDbInstance.AddCommand(&DmcCommandHeartBeat{cmdAtt: CommandAttribute{CommandName: "dmc_heart_beat", IsProvidedResult: false}}, "dmc_heart_beat")

                ///////////////////////////////////// dmc_unregister /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_unregister", DmcUnregister{})
                commandDbInstance.AddCommand(&DmcCommandUnregister{cmdAtt: CommandAttribute{CommandName: "dmc_unregister", IsProvidedResult: false}}, "dmc_unregister")

                ///////////////////////////////////// dmc_stream_query /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_stream_query", DmcStreamQuery{})
                commandDbInstance.AddCommand(&DmcCommandStreamQuery{cmdAtt: CommandAttribute{CommandName: "dmc_stream_query", IsProvidedResult: false}}, "dmc_stream_query")

                ///////////////////////////////////// dmc_all_stream_update /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_all_stream_update", DmcAllStreamUpdate{})
                commandDbInstance.AddCommand(&DmcCommandAllStreamUpdate{cmdAtt: CommandAttribute{CommandName: "dmc_all_stream_update", IsProvidedResult: false}}, "dmc_all_stream_update")

                ///////////////////////////////////// dmc_capability_update /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_capability_update", DmcCapabilityUpdate{})
                commandDbInstance.AddCommand(&DmcCommandCapabilityUpdate{cmdAtt: CommandAttribute{CommandName: "dmc_capability_update", IsProvidedResult: false}}, "dmc_capability_update")

                ///////////////////////////////////// dmc_stream_update /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_stream_update", DmcStreamUpdate{})
                commandDbInstance.AddCommand(&DmcCommandStreamUpdate{cmdAtt: CommandAttribute{CommandName: "dmc_stream_update", IsProvidedResult: false}}, "dmc_stream_update")

                ///////////////////////////////////// dmc_get_dms_request /////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_get_dms_request", DmcGetDmsRequest{})
                commandDbInstance.AddCommand(&DmcCommandGetDmsRequest{cmdAtt: CommandAttribute{CommandName: "dmc_get_dms_request", IsProvidedResult: true}}, "dmc_get_dms_request")

                ///////////////////////////////////// dmc_get_dms_response ////////////////////////////
                commandDbInstance.JsonReflect.RegisterName("dmc_get_dms_response", DmcGetDmsResponse{})
                commandDbInstance.AddCommand(&DmcCommandGetDmsResponse{cmdAtt: CommandAttribute{CommandName: "dmc_get_dms_response", IsProvidedResult: false}}, "dmc_get_dms_response")
        })
        return commandDbInstance
}

func (cdb *CommandDb) AddCommand(cmd Command, cmdName string) {
        cdb.CommandMap = cmd
}

func (cdb *CommandDb) GetCommand(name string) (Command, error) {

        if cdb.CommandMap != nil {
                return cdb.CommandMap, nil
        }

        err := errors.New("This command is not exist!")

        return nil, err
}
页: [1] 2 3
查看完整版本: 一起学go语言啦