Go:地址中缺少端口

wfsdck30  于 2023-09-28  发布在  Go
关注(0)|答案(2)|浏览(93)

我想用Go/Golang做一个简单的Web应用程序。我的主要功能代码是:

func main() {
fileServer := http.FileServer(http.Dir("./static"))
http.Handle("/", fileServer)
http.HandleFunc("/form", formHandler)
http.HandleFunc("/hello", helloHandler)

fmt.Printf("Starting server at port 8080\n")
if err := http.ListenAndServe(":8080", nil); err != nil {
    log.Fatal(err)
}

}
当我运行go run main.go时,我得到以下错误:

listen tcp: address ;8080: missing port in address
exit status 1

我尝试使用lsof -i :8080命令,但没有得到任何输出。将端口从:8080更改为:80没有影响。nc -l :8080也不行。
如何解决此问题?
PS:我用的是Fedora OS

6jjcrrmo

6jjcrrmo1#

请尝试以下代码:

func main() {
    fileServer := http.FileServer(http.Dir("./static"))

    httpf := http.NewServeMux()
    httpf.Handle("/", fileServer)
    httpf.HandleFunc("/form", settings.Grp_Insert)
    httpf.HandleFunc("/hello", settings.Grp_Insert)

    srv := &http.Server{
        ReadTimeout:       3 * time.Second,
        WriteTimeout:      6 * time.Second,
        Addr:              "localhost:8080",
        IdleTimeout:       15 * time.Second,
        ReadHeaderTimeout: 3 * time.Second,
        Handler:           httpf,
    }

    fmt.Printf("Starting server at port 8080\n")
    if err := srv.ListenAndServe(); err != nil {
        log.Fatal(err)
    }
}
qco9c6ql

qco9c6ql2#

我知道这是旧的,但以防任何人谁可能有这个问题。尝试将端口指定为“localhost:8080”而不是“:8080”
在这种情况下,代码应该是这样的:

func main() {
     fileServer := http.FileServer(http.Dir("./static"))
     http.Handle("/", fileServer)
     http.HandleFunc("/form", formHandler)
     http.HandleFunc("/hello", helloHandler)

     fmt.Printf("Starting server at port 8080\n")
     if err := http.ListenAndServe("localhost:8080", nil); err != nil {
        log.Fatal(err)
     }

相关问题