来自 linter 的 goconst 警告

goconst warnings from linter

我正在使用 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 (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.
        }

}

我通过这种方式设置了大量功能。它使得在一个地方处理任何情况(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 的每个实例进行一次;最终,对我来说这是一个巨大的列表(因此是一个巨大的错误列表)。

我看不到 'ignore' Atom 警告的明显方法,所以我想禁用 linter,这对于更严重的警告不是很好...

这只是一个警告,表明您在多个地方重复使用相同的字符串文字。这可能会有问题,因为字符串文字很容易在不注意的情况下被拼错。解决方案是改用常量。这在您的情况下变得非常容易,因为所有(标准)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, ...)

编译失败