首页 > 解决方案 > 在 Go 中基于 net/http 包打开 html 文件

问题描述

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

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

就像index.html,但我想替换index.htmlHome.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")
    }
}

如何重新编写此代码?

这个问题的关键词是什么?

标签: httpgowebserver

解决方案


要将任何静态文件提供给端点,您可以使用http.ServeFile或者http.ServeContent如果您想要更多控制。

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

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

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


推荐阅读