在Go中基于net / http包打开html文件

时间:2018-08-04 05:38:56

标签: http go web server

我是Go语言的初学者。 我尝试在本地计算机上构建静态Web服务器。 实际上,我已经读过How do you serve a static html file using a go web server?

我的问题是,如果我有Home.html。 链接Home.html时,我想打开localhost:7777

就像index.html,但我想将index.html替换为Home.html

这是我的代码:

package main
import (
    "fmt"
    "net/http"
    "log"
)

func helloHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "hello world!")
}
func main() {

    http.HandleFunc("/", helloHandler)
    // 
    err := http.ListenAndServe(":7777", nil)
    if err != nil {
        log.Fatal("ListenAndServe", err)
    } else {
        log.Println("listen 7777")
    }
}

如何重新编写此代码?

此问题有哪些关键字?

1 个答案:

答案 0 :(得分:2)

要将任何静态文件提供给端点,如果需要更多控制,可以使用http.ServeFilehttp.ServeContent

在这种情况下,您可以编写:

func helloHandler(w http.ResponseWriter, r *http.Request) {
    http.ServeFile(w,r,"Home.html")
}

确保将名称设置为Home.html的路径。从其他地方运行时,使用相对路径,程序可能找不到文件。