Golang如何将HTML页面渲染到浏览器?

Golang如何将HTML页面渲染到浏览器? 我编写了一段代码,使用渲染器包将HTML呈现到浏览器:

package main

import (
// "github.com/gorilla/mux"
"net/http"
"github.com/thedevsaddam/renderer"
)

var rnd *renderer.Render

func init() {
opts := renderer.Options{
ParseGlobPattern: "./src/templates/*.html",
}
rnd = renderer.New(opts)
}

func main() {
mux := http.NewServeMux()
//r:=mux.NewRouter()
mux.HandleFunc("/login", loginHandler)
port:=":8085"
http.ListenAndServe(port, mux)
}

func loginHandler(w http.ResponseWriter, r *http.Request) {
rnd.HTML(w, http.StatusOK, "login", nil)
}

// login.html 放置在 src/templates 文件夹中


更多关于Golang如何将HTML页面渲染到浏览器?的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于Golang如何将HTML页面渲染到浏览器?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


以下是使用 github.com/thedevsaddam/renderer 包将 HTML 页面渲染到浏览器的正确实现。您的代码基本正确,但需要确保模板文件路径和路由处理正确配置。

完整示例代码:

package main

import (
	"net/http"
	"github.com/thedevsaddam/renderer"
)

var rnd *renderer.Render

func init() {
	opts := renderer.Options{
		ParseGlobPattern: "./templates/*.html", // 修正模板路径
	}
	rnd = renderer.New(opts)
}

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/login", loginHandler)
	
	port := ":8085"
	http.ListenAndServe(port, mux)
}

func loginHandler(w http.ResponseWriter, r *http.Request) {
	// 渲染 login.html 模板
	err := rnd.HTML(w, http.StatusOK, "login", nil)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
}

关键点说明:

  1. 模板路径配置:确保 ParseGlobPattern 指向正确的模板目录。如果模板文件在项目根目录的 templates 文件夹中,使用 "./templates/*.html"

  2. 错误处理rnd.HTML() 方法返回错误,应该进行检查和处理

  3. 文件结构示例

project/
├── main.go
└── templates/
    └── login.html
  1. login.html 示例内容
<!DOCTYPE html>
<html>
<head>
    <title>Login Page</title>
</head>
<body>
    <h1>User Login</h1>
    <form>
        <input type="text" placeholder="Username">
        <input type="password" placeholder="Password">
        <button type="submit">Login</button>
    </form>
</body>
</html>

运行程序后,访问 http://localhost:8085/login 即可看到渲染的 HTML 页面。

回到顶部