V
V
Vadim Rublev2021-12-15 20:59:19
go
Vadim Rublev, 2021-12-15 20:59:19

Why is the Go server not opening the page?

Why does this server open the page:

func main() {
    fmt.Println("Server is listening port... :900")

  http.ListenAndServe("127.0.0.1:900", http.FileServer(http.Dir("F:/Projects/www/domen.com/")))
}


The URL localhost:900 opens the index.* file from the specified directory.

But this one doesn't (the browser, or Go?, reports "404 page not found"):
func allRout(w http.ResponseWriter, r *http.Request) {
    http.FileServer(http.Dir("F:/Projects/www/domen.com/")).ServeHTTP(w, r)
}

func main() {
    fmt.Println("Server (with TLS) is listening port... :600")
     
    var mux = http.NewServeMux()
    
    mux.HandleFunc("/", allRout)             // Общий маршрут.
     
    var serv = &http.Server {
        Addr:         "127.0.0.1:600",
        ReadTimeout:  15 * time.Second,
        WriteTimeout: 15 * time.Second,
    }
    log.Fatal(serv.ListenAndServeTLS("F:/Projects/www/domen.com/cert.pem", "F:/Projects/www/domen.com/key.pem"))
}


The index.html file from the specified directory should also open.
I tried the URL: localhost:600 , localhost:600/index.html
OS Windows 10.

PS And it used to work fine, but it suddenly broke.
The firewall allows all local ports.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2021-12-16
@Vadim Rublev

Didn't notice right away, you forgot to tell the server to use your mux

var serv = &http.Server {
        Addr:         "127.0.0.1:600",
        ReadTimeout:  15 * time.Second,
        WriteTimeout: 15 * time.Second,
        Handler: mux, // <---- здесь
    }

By the way, don't do this:
func allRout(w http.ResponseWriter, r *http.Request) {
    http.FileServer(http.Dir("F:/Projects/www/domen.com/")).ServeHTTP(w, r)
}

You are essentially creating a file server with every request, and after the request it is removed by the garbage collector. You need to create it once (call http.FileServer(...)), and then call ServeHTTP in the handler on the ready server.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question