【问题标题】:goconst warnings from linter来自 linter 的 goconst 警告
【发布时间】:2018-03-05 12:03:24
【问题描述】:

我正在使用 Atom 开发我的 Go 应用程序。 Atom 中的 Linter 报告了一个奇怪的警告,我不明白这是怎么回事。我应该永远忽略警告,还是有其他方法可以实现?

错误: Warning goconst 3 other occurrence(s) of "GET" found in: routes_pages.go:384:8 routes_pages.go:443:7 routes_pages.go:536:7 (goconst) 198:8

详情:

我在文件“app.go”中有路线:

a.Router.HandleFunc("/login", a.PageLogin)
a.Router.HandleFunc("/register", a.PageRegister)
a.Router.HandleFunc("/event/add", a.PageEventCreate)

在“routes_pages.go”文件中,我有这样的 func 定义:

func (a *App) PageEventCreate(w http.ResponseWriter, r *http.Request) {

    switch r.Method {
        case "GET":
            // Serve the resource.
        case "POST":
            // Create a new record.
        case "PUT":
            // Update an existing record.
        case "DELETE":
            // Remove the record.
        default:
            // Give an error message.
    }

}



func (a *App) PageLogin(res http.ResponseWriter, req *http.Request) {
        switch r.Method {
            case "GET":
                // Serve the resource.
            case "POST":
                // Create a new record.
            case "PUT":
                // Update an existing record.
            case "DELETE":
                // Remove the record.
            default:
                // Give an error message.
        }

}

我有很多这样的 func 设置。它使在一个地方处理任何情况(GET、POST 等)变得容易。

Atom 中的 Linter 对此存在问题。它为每个项目报告一个警告,例如:

Warning goconst 3 other occurrence(s) of "GET" found in: routes_pages.go:384:8 routes_pages.go:443:7 routes_pages.go:536:7 (goconst)    198:8

此警告多次出现;使用 GET、PUT、DELETE 等对每个 switch/case 实例执行一次;最终,对我来说这是一个巨大的列表(因此是一个巨大的错误列表)。

我认为没有明显的方法可以“忽略”Atom 中的警告,所以我只想禁用 linter,这对于更严重的警告来说并不是很好......

【问题讨论】:

    标签: go linter


    【解决方案1】:

    这只是一个警告,您在多个地方重复使用相同的字符串文字。这可能是有问题的,因为字符串文字很可能在没有注意到的情况下拼写错误。解决方案是改用常量。在您的情况下,这非常容易,因为所有(标准)HTTP 动词已经是 http 包导出的常量。只需更新您的字符串文字以使用 contant 版本:

    func (a *App) PageLogin(res http.ResponseWriter, req *http.Request) {
            switch r.Method {
                case http.MethodGet:
                    // Serve the resource.
                case http.MethodPost:
                    // Create a new record.
                case http.MethodPut:
                    // Update an existing record.
                case http.MethodDelete:
                    // Remove the record.
                default:
                    // Give an error message.
            }
    }
    

    通过使用常量,您可以防止意外输入错误。示例:

    req, err := http.NewRequest("DLETE", ...)
    

    不会导致编译时错误(甚至可能不会导致运行时错误,具体取决于程序的其余逻辑),但是

    req, err := http.NewRequest(http.MethodDlete, ...)
    

    将无法编译。

    【讨论】:

      猜你喜欢
      • 2022-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-21
      • 2021-10-27
      相关资源
      最近更新 更多