gpt4 book ai didi

url - Golang 提供主页并提供模板页面

转载 作者:数据小太阳 更新时间:2023-10-29 03:33:33 26 4
gpt4 key购买 nike

我希望在 url="/"处有一个静态着陆页,然后使用模板提供任何文件 url="/"+file。

我的模板可以很好地处理这段代码

package main

import (
"html/template"
"log"
"net/http"
"os"
"path"
)

func main() {
fs := http.FileServer(http.Dir("static"))
http.Handle("/static/", http.StripPrefix("/static/", fs))

http.HandleFunc("/", serveTemplate)

log.Println("Listening...")
http.ListenAndServe(":5000", nil)
}

func serveTemplate(w http.ResponseWriter, r *http.Request) {
lp := path.Join("templates", "layout.html")
fp := path.Join("templates", r.URL.Path)

// Return a 404 if the template doesn't exist
info, err := os.Stat(fp)
if err != nil {
if os.IsNotExist(err) {
http.NotFound(w, r)
return
}
}

// Return a 404 if the request is for a directory
if info.IsDir() {
http.NotFound(w, r)
return
}

templates, err := template.ParseFiles(lp, fp)
if err != nil {
log.Print(err)
http.Error(w, "500 Internal Server Error", 500)
return
}
templates.ExecuteTemplate(w, "layout", nil)
}

所以这很好用。基本上,我认为我需要做两件事。第一,在处理单个 html 文件的 main() 函数中添加另一个 http.Handle 或 http.HandlerFunc,然后让我的错误检查器重定向到那里,而不是抛出 404 错误。

请帮助我如何做到这一点或提供更好的解决方案?

最佳答案

我建议通读:http://golang.org/doc/articles/wiki/#tmp_6 - 它涵盖了大部分内容。

具体来说:

  • 您阻止了每个读取文件系统的请求(糟糕!);
  • 然后您将在每次请求时(缓慢地)解析您的模板文件;
  • 使用 URL 路径的一部分直接从文件系统读取是一个巨大的安全问题(即使 Go 试图逃避它,也希望有人能击败它)。对此要非常小心

您还应该在程序启动期间(即在您的 main() 开始时)仅解析一次模板。使用 tmpl := template.Must(template.ParseGlob("/dir")) 提前从目录中读取所有模板 - 这将允许您从 route 查找模板. html/template文档很好地涵盖了这一点。

请注意,当您尝试从路由匹配的模板在您的处理程序中不存在时,您需要编写一些逻辑来捕获。

我还会考虑使用 gorilla/mux如果你想要更多的功能。您可以编写一个未找到的处理程序,该处理程序使用 302(临时重定向)重定向到 /,而不是引发 404。

r := mux.NewRouter()

r.HandleFunc("/:name", nameHandler)
r.HandleFunc("/", rootHandler)
r.NotFoundHandler(redirectToRoot)
http.Handle("/", r)

log.Fatal(http.ListenAndServe(":8000", nil))

func redirectToRoot(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/", http.StatusSeeOther)
}

希望对您有所帮助。

关于url - Golang 提供主页并提供模板页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24111923/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com