剖析Go编写的Socket服务器模块解耦及基础模块的设计

2020-01-28 11:56:52于丽

    Content interface{}            `json:"content"` 

 
type Controller interface { 
    Excute(message Msg) []byte 

 
var routers [][2]interface{} 
 
func Route(judge interface{} ,controller Controller) { 
    switch judge.(type) { 
    case func(entry Msg)bool:{ 
        var arr [2]interface{} 
        arr[0] = judge 
        arr[1] = controller 
        routers = append(routers,arr) 
    } 
    case map[string]interface{}:{ 
        defaultJudge:= func(entry Msg)bool{ 
            for keyjudge , valjudge := range judge.(map[string]interface{}){ 
                val, ok := entry.Meta[keyjudge] 
                if !ok { 
                    return false 
                } 
                if val != valjudge { 
                    return false 
                } 
            } 
            return true 
        } 
        var arr [2]interface{} 
        arr[0] = defaultjudge 
        arr[1] = controller 
        routers = append(routers,arr) 
        fmt.Println(routers) 
        } 
    default: 
        fmt.Println("Something is wrong in Router") 
    } 


      通过自定义接口Router,我们将匹配规则judge和对应的controller封装了进去,然后在Server端负责接收socket发送信息的函数handleConnection那里再实现Router内部的遍历即可: