用 Go 做一个简单的 FileServer 和 Localhost 拒绝连接

Making a Simple FileServer with Go and Localhost Refused to Connect

现在我从一本书中提取了以下代码。

package main

import (
    "net/http"
)

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

我希望它可以列出 main.go 文件夹中的所有文件,但是当我浏览到:
https://localhost:8001
我只能看到:

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

我使用 LiteIDE 构建和 运行 程序。单击 BuildAndRun 后,将显示以下消息。

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.

为什么以及如何解决?

您的系统找不到证书文件。:
此错误意味着您需要 "rui.crt" 文件以及主二进制文件。
如果您没有证书,请参阅:How to create a self-signed certificate with openssl?

然后将 "server.pem"、"server.key" 文件复制到您的二进制 (.exe) 文件目录

和运行此示例代码(用于测试):

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)
    }
}

然后打开网页:https://127.0.0.1/
如果防火墙弹出说是,
如果你看到 There is a problem with this website’s security certificate. 说继续(前进)。

输出:

*Hello World
*