add html/tmpl for status err page

This commit is contained in:
wjqserver 2025-04-22 20:56:27 +08:00
parent d79aeaaacd
commit 493ac28b59
4 changed files with 183 additions and 62 deletions

View file

@ -1,10 +1,12 @@
package proxy
import (
"bytes"
"fmt"
"ghproxy/auth"
"ghproxy/config"
"ghproxy/rate"
"html/template"
"io/fs"
"github.com/cloudwego/hertz/pkg/app"
@ -98,13 +100,81 @@ func InitErrPagesFS(pages fs.FS) error {
return nil
}
type ErrorPageData struct {
StatusCode int
StatusDesc string
StatusText string
HelpInfo string
ErrorMessage string
}
func ErrPageUnwarper(errInfo *GHProxyErrors) ErrorPageData {
return ErrorPageData{
StatusCode: errInfo.StatusCode,
StatusDesc: errInfo.StatusDesc,
StatusText: errInfo.StatusText,
HelpInfo: errInfo.HelpInfo,
ErrorMessage: errInfo.ErrorMessage,
}
}
func ErrorPage(c *app.RequestContext, errInfo *GHProxyErrors) {
pageData, _ := htmlTemplateRender(errPagesFs, ErrPageUnwarper(errInfo))
/*
if err != nil {
c.JSON(errInfo.StatusCode, map[string]string{"error": errInfo.ErrorMessage})
logDebug("Error reading page.tmpl: %v", err)
return
}
*/
fmt.Printf("errInfo: %s\n", errInfo)
c.Data(errInfo.StatusCode, "text/html; charset=utf-8", pageData)
return
}
func NotFoundPage(c *app.RequestContext) {
pageData, err := fs.ReadFile(errPagesFs, "404.html")
/*
pageData, err := fs.ReadFile(errPagesFs, "404.html")
if err != nil {
c.JSON(404, map[string]string{"error": "Not Found"})
logDebug("Error reading 404.html: %v", err)
return
}
*/
pageData, err := htmlTemplateRender(errPagesFs, ErrorPageData{
StatusCode: 404,
StatusDesc: "Not Found",
StatusText: "The requested URL was not found on this server.",
ErrorMessage: "The requested URL was not found on this server.",
})
if err != nil {
c.JSON(404, map[string]string{"error": "Not Found"})
logDebug("Error reading 404.html: %v", err)
return
}
c.Data(404, "text/html; charset=utf-8", pageData)
return
}
func htmlTemplateRender(fsys fs.FS, data interface{}) ([]byte, error) {
tmplPath := "page.tmpl"
tmpl, err := template.ParseFS(fsys, tmplPath)
if err != nil {
return nil, fmt.Errorf("error parsing template: %w", err)
}
if tmpl == nil {
return nil, fmt.Errorf("template is nil")
}
// 创建一个 bytes.Buffer 用于存储渲染结果
var buf bytes.Buffer
err = tmpl.Execute(&buf, data)
if err != nil {
return nil, fmt.Errorf("error executing template: %w", err)
}
// 返回 buffer 的内容作为 []byte
return buf.Bytes(), nil
}