duanjia1870 2017-06-28 20:50 采纳率: 0%
浏览 363
已采纳

如何避免在Go中使用长的switch-case语句

I'm writing a chat bot in Go and wondering how can I avoid a long switch-case statement similar to this one:

switch {

// @bot search me HMAC
case strings.Contains(message, "search me"):
    query := strings.Split(message, "search me ")[1]
    return webSearch(query), "html"

// @bot thesaurus me challenge
case strings.Contains(message, "thesaurus me"):
    query := strings.Split(message, "thesaurus me ")[1]
    return synonyms(query), "html"

Should I define those handlers each in a separate package or should I just use structs and interfaces? Which method will allow me to have a good structure, avoid switch-case and let external developers to easier create handlers?

I think packages will be a better choice but I'm not sure how to register the handlers with the main bot. Would appreciate an example.

  • 写回答

1条回答 默认 最新

  • drkrsx3135168 2017-06-28 21:27
    关注

    You could use a map[string]command similar to how the net/http package registers handlers. Something akin to this:

    https://play.golang.org/p/9YzHyLodAQ

    package main
    
    import (
        "fmt"
        "errors"
    )
    
    type BotFunc func(string) (string, error)
    
    type BotMap map[string]BotFunc
    
    var Bot = BotMap{}
    
    func (b BotMap) RegisterCommand(command string, f BotFunc) error {
        if _, exists := b[command]; exists {
            return errors.New("command already exists")
        }
        b[command] = f
        return nil
    }
    
    func (b BotMap) Execute(statement string) (string, error) {
        // parse out command and query however you choose (not this way obviously)
        command := statement[:9]
        query := statement[10:]
    
        return b.ExecuteQuery(command, query)
    }
    
    func (b BotMap) ExecuteQuery(command, query string) (string, error) {
        if com, exists := b[command]; exists {
            return com(query)
        }
        return "", errors.New("command doesn't exist")
    
    }
    
    func main() {
        err := Bot.RegisterCommand("search me", func(query string) (string, error) {
            fmt.Println("search", query)
            return "searched", nil
        })
        if err != nil {
            fmt.Println(err)
            return
        }
        err = Bot.RegisterCommand("thesaurus me", func(query string) (string, error) {
            fmt.Println("thesaurus", query)
            return "thesaurused", nil
        })
        if err != nil {
            fmt.Println(err)
            return
        }
    
        result, err := Bot.Execute("search me please")
        if err != nil {
            fmt.Println(err)
            return
        }
        fmt.Println(result)
    }
    

    Obviously there's a lot of checks missing here, but this is the basic idea.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分