http - 在 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.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")
}
}
如何重新编写此代码?
这个问题的关键词是什么?
解决方案
要将任何静态文件提供给端点,您可以使用http.ServeFile
或者http.ServeContent
如果您想要更多控制。
在这种情况下,您可以编写:
func helloHandler(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w,r,"Home.html")
}
请务必将名称设置为Home.html
. 从其他地方运行时使用相对路径时,程序可能找不到文件。
推荐阅读
- javascript - 将一个对象数组中的项目作为数组包含在第二个对象数组的每个对象中(按键)
- javascript - 使用 Nonce 从脚本中读取 Javascript 变量
- android - Android:从应用程序以编程方式打开开发人员选项时遇到“静默”崩溃
- r - 为什么我在 R 中收到 QQLine 绘图错误
- php - Http 发送 Post 请求但 Curl 失败
- parallel-processing - MPI,如果使用非阻塞 i_send 或 i_recv,如果最后有等待,哪个先走有关系吗?
- node.js - 使用(本地、谷歌、脸书)的 MongoDB 用户模式设计身份验证
- java - groovy “BUG!源单元 sun.reflect.annotation.TypeNotPresentExceptionProxy 阶段‘语义分析’中的异常” JAVA SPRING BOOT 1.x -> 2.x
- sql - 每天计数返回错误值
- c++ - tictactoe:检查无效输入