Golang中解决Panic: listen tcp :80: bind: permission denied错误

Golang中解决Panic: listen tcp :80: bind: permission denied错误 你好。我遇到了panic。Windows防火墙中80端口是开放的。我使用的是WSL:Ubuntu。这个问题是Ubuntu特有的吗?

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		render(w, "test.page.gohtml")
	})

	fmt.Println("Starting front end service on port 80")
	err := http.ListenAndServe(":80", nil)
	if err != nil {
		log.Panic(err)
	}
}

func render(w http.ResponseWriter, t string) {

	partials := []string{
		"./cmd/web/templates/base.layout.gohtml",
		"./cmd/web/templates/header.partial.gohtml",
		"./cmd/web/templates/footer.partial.gohtml",
	}

	var templateSlice []string
	templateSlice = append(templateSlice, fmt.Sprintf("./cmd/web/templates/%s", t))

	for _, x := range partials {
		templateSlice = append(templateSlice, x)
	}

	tmpl, err := template.ParseFiles(templateSlice...)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	if err := tmpl.Execute(w, nil); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

更多关于Golang中解决Panic: listen tcp :80: bind: permission denied错误的实战教程也可以访问 https://www.itying.com/category-94-b0.html

3 回复

尝试对二进制文件使用 “chmod +x” 命令

更多关于Golang中解决Panic: listen tcp :80: bind: permission denied错误的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


如果你指的是 front-end/cmd/web$ chmod +x main.go 这个命令不起作用。(

这个错误是因为在Linux系统(包括WSL中的Ubuntu)上,绑定1024以下的端口需要root权限。80端口是特权端口,普通用户无法直接监听。

解决方案是使用sudo运行程序,或者将端口改为1024以上的端口(如8080)。

示例代码修改端口为8080:

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		render(w, "test.page.gohtml")
	})

	fmt.Println("Starting front end service on port 8080")
	err := http.ListenAndServe(":8080", nil)  // 改为8080端口
	if err != nil {
		log.Panic(err)
	}
}

如果需要坚持使用80端口,可以通过sudo运行程序:

sudo go run main.go

或者编译后使用sudo运行:

go build -o app
sudo ./app

另外,也可以在WSL中通过以下命令检查端口占用情况:

sudo netstat -tlnp | grep :80

如果80端口已被其他进程占用,需要先停止占用该端口的进程。

回到顶部