Golang模板函数返回index.html的内容而不是页面

问题描述 投票:0回答:1

我尝试通过 本教程 创建 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)

html go http templates
1个回答
0
投票

根据评论,第一行应该是

<!DOCTYPE html>
playground)。请参阅 MDN 了解更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.