Golang中Gorilla/mux与1.20版本的兼容性探讨

Golang中Gorilla/mux与1.20版本的兼容性探讨 我将服务器升级到 Go 1.20 后,立即遇到了 gorilla/mux 与 ListenAndServe("59995", handle(router))) 函数的问题;当我运行项目时,响应是“Listen and Serve listen tcp: address tcp/ 59995: unknown port”。我降级到 1.19 版本后,它就能正常工作(代码没有任何改动)。如果有人遇到过同样的问题,并能提供如何修复此错误的建议,我将非常感激。

2 回复

你好,你确定它在 1.19 版本上能工作吗?

ListenAndServe() 接受一个“地址字符串”作为输入;你应该传递类似这样的参数:

ListenAndServe(":59995", handle(router))

更多关于Golang中Gorilla/mux与1.20版本的兼容性探讨的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


在 Go 1.20 中,net.Listenhttp.ListenAndServe 对地址格式的验证变得更加严格。错误信息表明 Go 1.20 不再接受 "59995" 这种格式的地址,因为它缺少主机部分。

解决方案: 需要在端口号前添加 : 前缀,或者明确指定主机地址。

修改前:

http.ListenAndServe("59995", handle(router))

修改后(推荐):

http.ListenAndServe(":59995", handle(router))

或者指定本地主机:

http.ListenAndServe("localhost:59995", handle(router))

完整示例:

package main

import (
    "net/http"
    "github.com/gorilla/mux"
)

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello World"))
    })

    // 正确的地址格式
    err := http.ListenAndServe(":59995", router)
    if err != nil {
        panic(err)
    }
}

这个修改与 gorilla/mux 本身无关,而是 Go 1.20 对网络地址格式验证的变更。降级到 Go 1.19 能正常工作是因为旧版本对地址格式的解析更宽松。

回到顶部