Golang中网页内容为空,如何修改代码解决

Golang中网页内容为空,如何修改代码解决 main.go

package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"os"
	"strings"
)

func homeHandler(w http.ResponseWriter, r *http.Request) {
	var lang = []string{"en", "zh", "es"}
	// 读取Accept-Language头部
	// acceptLanguage := r.Header.Get("Accept-Language")

	// var langCode string

	// langCode = strings.Split(acceptLanguage, ",")[0][:2]
	langCode := strings.Split(r.Header.Get("Accept-Language"), ",")[0][:2]
	// fmt.Println("Trying language", langCode)

	found := false
	for _, l := range lang {
		if l == langCode {
			found = true
			break
		}
	}
	if !found {
		langCode = "en"
	}

	// dir, err := os.Getwd()
	// if err != nil {
	// 	log.Fatalf("Failed to get working directory: %v", err)
	// }
	// fmt.Println("Current Working Directory:", dir)

	url := "public/tmpl/" + langCode + "/"
	templates := []string{url + "index.html", url + "submenu.html", url + "content.html"}

	// url := filepath.Join(dir, "public/tmpl/", langCode)
	// 定义模板文件列表
	// templates := []string{url + "/index.html", url + "/submenu.html", url + "/content.html"}
	// fmt.Println(templates)
	// templates := []string{
	// 	filepath.Join(dir, "public/tmpl", langCode, "index.html"),
	// 	filepath.Join(dir, "public/tmpl", langCode, "submenu.html"),
	// 	filepath.Join(dir, "public/tmpl", langCode, "content.html"),
	// }

	// 验证模板文件是否存在
	for _, file := range templates {
		if _, err := os.Stat(file); os.IsNotExist(err) {
			log.Fatalf("Template file %s not found.", file)
		}
	}

	// fmt.Println(templates)

	// 加载模板
	tmpl := template.Must(template.ParseFiles(templates...))
	fmt.Println("Loaded templates:", tmpl.Templates())

	data := struct {
		Title string
	}{
		Title: "我的主页",
	}

	if err := tmpl.ExecuteTemplate(w, templates[0], data); err != nil {
		log.Printf("Error executing template: %v", err)
		// http.Error(w, "Error executing template", http.StatusInternalServerError)
		return
	}
}

func main() {
	http.HandleFunc("/", homeHandler)

	//启动服务器
	// fmt.Println("Server is listening on :8080")
	log.Println("Starting server on :8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal("Could not start server: %v", err)
	}
}

index.html

{{ define "index" }}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ .Title }}</title>
</head>
<body>
    {{ template "submenu" . }}
    {{ template "content" . }}
</body>
</html>
{{ end }}

content.html

{{ define "content" }}
<main>
    <!-- 正文内容 -->
    <h1>嗨,欢迎你来访问我的个人主页,谢谢!</h1>
</main>
{{ end }}

submenu.html

{{ define "submenu" }}
<aside>
    <!-- 子菜单内容 -->
    <h1>首页、关于我、计算机、音乐、旅游</h1>
</aside>
{{ end }}

我遇到以下错误:

go run "/Users/douxiaobo/Documents/Practice in Coding/Personal_Website_Go/main.go"
Loaded templates: [0x14000183350 0x140001835f0 0x14000183620 0x14000183740 0x14000183770 0x140001838c0]
2024/07/05 16:45:40 Error executing template: html/template: "/Users/douxiaobo/Documents/Practice in Coding/Personal_Website_Go/public/tmpl/zh/index.html" is undefined
Loaded templates: [0x140001d6150 0x14000183b60 0x14000183e00 0x14000183e30 0x14000183f50 0x140001d6000]
2024/07/05 16:45:40 Error executing template: html/template: "/Users/douxiaobo/Documents/Practice in Coding/Personal_Website_Go/public/tmpl/zh/index.html" is undefined
^Csignal: interrupt
douxiaobo@192 Personal_Website_Go % 

请告诉我如何在代码中进行修改。非常感谢。


更多关于Golang中网页内容为空,如何修改代码解决的实战教程也可以访问 https://www.itying.com/category-94-b0.html

6 回复

谢谢。我从未学过 Gin。

更多关于Golang中网页内容为空,如何修改代码解决的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


我明白了。让我试试。谢谢。

请注意,index 函数将被调用两次,因此最好将你的初始化代码移到 init() 函数中,或者在执行服务器之前进行初始化。

关于错误信息,看起来你的 .html 文件无法被正确解析。建议先尝试只处理一个文件…

{{ define "submenu" }}
<aside>
    <!-- 子菜单内容 -->
    <h1>首页、关于我、计算机、音乐、旅游</h1>
</aside>
{{ end }}

好的。运行正常。谢谢。

我正在使用Gin Web框架,所以情况可能有所不同。但我必须在模板中使用与定义中完全相同的命名。 因此,也许可以尝试将

{{ define "index" }}

改为

{{ define "index.html" }}

子菜单和内容部分也同理 :)

问题在于模板执行时使用了错误的模板名称。在homeHandler函数中,tmpl.ExecuteTemplate(w, templates[0], data)使用了文件路径作为模板名称,但应该使用模板定义中的名称。

修改homeHandler函数中的模板执行部分:

// 修改前:
if err := tmpl.ExecuteTemplate(w, templates[0], data); err != nil {
    log.Printf("Error executing template: %v", err)
    return
}

// 修改后:
if err := tmpl.ExecuteTemplate(w, "index", data); err != nil {
    log.Printf("Error executing template: %v", err)
    return
}

完整修正后的homeHandler函数:

func homeHandler(w http.ResponseWriter, r *http.Request) {
	var lang = []string{"en", "zh", "es"}
	langCode := strings.Split(r.Header.Get("Accept-Language"), ",")[0][:2]

	found := false
	for _, l := range lang {
		if l == langCode {
			found = true
			break
		}
	}
	if !found {
		langCode = "en"
	}

	url := "public/tmpl/" + langCode + "/"
	templates := []string{url + "index.html", url + "submenu.html", url + "content.html"}

	for _, file := range templates {
		if _, err := os.Stat(file); os.IsNotExist(err) {
			log.Fatalf("Template file %s not found.", file)
		}
	}

	tmpl := template.Must(template.ParseFiles(templates...))

	data := struct {
		Title string
	}{
		Title: "我的主页",
	}

	if err := tmpl.ExecuteTemplate(w, "index", data); err != nil {
		log.Printf("Error executing template: %v", err)
		return
	}
}

ExecuteTemplate方法的第二个参数应该是模板定义中的名称(在{{ define "index" }}中指定的"index"),而不是文件路径。模板系统根据定义名称来查找模板,而不是根据文件名。

回到顶部