Search code examples
golocalhostfileserver

Making a Simple FileServer with Go and Localhost Refused to Connect


Now I have the following code extracted from a book.

package main

import (
    "net/http"
)

func main() {
    h := http.FileServer(http.Dir("."))
    http.ListenAndServeTLS(":8001", "rui.crt", "rui.key", h)
}

I expect it can list all the file in the folder of main.go but when I browse to:
https://localhost:8001
I can only see:

This site can’t be reached.  
localhost refused to connect.

I use LiteIDE to build and run the program. After BuildAndRun clicked, the following messages are shown.

F:/Go/bin/go.exe build -i [E:/Users/User/Desktop/codespace_v2.6.6/dev/server_side/golang/go_codespace_v2.1/server]
Success: process exited with code 0.
E:/Users/User/Desktop/codespace_v2.6.6/dev/server_side/golang/go_codespace_v2.1/server/server.exe  [E:/Users/User/Desktop/codespace_v2.6.6/dev/server_side/golang/go_codespace_v2.1/server]
Success: process exited with code 0.

Why and how can I fix it?


Solution

  • your system cannot find the certificate file.:
    this error means you need "rui.crt" file alongside with your main binary file.
    if you do not have certificate see: How to create a self-signed certificate with openssl?

    then copy "server.pem", "server.key" files to your binary(.exe) file directory

    and run this sample code (for test):

    package main
    
    import (
        "fmt"
        "log"
        "net/http"
    )
    
    type server struct {
    }
    
    func (s server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
        fmt.Fprint(w, "*Hello World\n*")
    }
    
    func main() {
        if err := http.ListenAndServeTLS(":443", "server.pem", "server.key", server{}); err != nil {
            log.Fatal(err)
        }
    }
    

    then open web page: https://127.0.0.1/
    if firewall poped up say yes,
    if you see There is a problem with this website’s security certificate. say continue (advance).

    output:

    *Hello World
    *