我尝试通过 本教程 创建 Web 应用程序,但是
localhost:3000 显示index.html 的内容而不是页面。我的代码有什么问题吗?
index.html 结果
main.go
package main
import (
"html/template"
"net/http"
"os"
)
var tpl = template.Must(template.ParseFiles("index.html"))
func indexHandler(w http.ResponseWriter, r *http.Request) {
tpl.Execute(w, nil)
}
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "3000"
}
mux := http.NewServeMux()
mux.HandleFunc("/", indexHandler)
http.ListenAndServe(":"+port, mux)
}
index.html
<DOCTYPE>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Orders</title>
<!-- <link rel="stylesheet" href="/assets/style.css"> -->
</head>
<body>
<h1>Orders12</h1>
</body>
</html>
go版本go1.22.4 windows/amd64
如果我用
tmpl.Execute(w, nil)
替换 w.Write([]byte("<h1>HELLO W</h1>"))
- 它可以工作,所以服务器没问题。也许问题出在tmpl.Execute(w, nil)