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

标签 http go web server

<分区>

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

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

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

如何重写这段代码?

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

最佳答案

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

在这种情况下,你可以这样写:

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

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

关于http - 在 Go 中打开基于 net/http 包的 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51682786/

相关文章:

javascript - 按下按钮时获取位于倍数 div 内的表单

javascript - 进入 getJSON 部分时,点击的项目是否超出范围

loops - 遍历字符串返回 int32

Go time.Parse() 得到 “month out of range” 错误

performance - Web 浏览器性能规则 "only 2 requests in parallel per hostname"是否仍然正确?

javascript - angularjs - 如何从 url 检索数据

error-handling - Golang错误处理错误

php - 我不应该在这个应用程序中使用 CakePHP 或 MVC 吗?

android - 捕获 android 应用程序 http 流量

java - HTTP 分块传输