Webpage is empty, I dont know how to modify in code

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 }}

I got error below:

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 % 

Please tell me how to modify in the code. Thank you very much.

Be aware that index will be called twice, so it is a good idea to move your initialization code to init() or before execute your server.
Regarding the error message it seem that your .html can not be parsed appropriately. Try only one file first…

I see. let me try. Thank you.

I’m using Gin web framework, so it might be different. But i have to use the exact naming in the template as in the definition.
So maybe try changing
{{ define "index" }}
to
{{ define "index.html" }}

Same goes for submenu and content :slight_smile:

Thank you. I neve learn Gin.

Okay. Running is fine. Thank you.

1 Like