jjzjj

golang 模板不适用于 httprouter

coder 2024-07-10 原文

我已经创建了嵌套模板,当我使用“net/http”和 http.HandelFunc 时它可以工作,但是,我决定继续使用“github.com/julienschmidt/httprouter”,因为我想要移动灵 active 现在我的模板不起作用,出现 404 错误。

拜托,你能帮忙吗?

目录结构

/
/main.go
/templates
/templates/tstats/file.go.html

此代码有效

func init() {
    tpl = template.Must(template.ParseGlob("templates/*.go.html"))
}
http.HandleFunc("/tstats/", serveTemplate)

func serveTemplate(w http.ResponseWriter, r *http.Request) {
    lp := filepath.Join("templates", "layout.html")
    fp := filepath.Join("templates", filepath.Clean(r.URL.Path))
    gh := filepath.Join("templates", "INC_Header.go.html")
    gn := filepath.Join("templates", "INC_Nav.go.html")
    gf := filepath.Join("templates", "INC_Footer.go.html")
    //log.Println(r.URL.Path)

tpl, err := template.ParseFiles(lp, fp, gh, gn, gf)
if err := tpl.ExecuteTemplate(w, "layout", nil); err != nil {
    log.Println(err.Error())
    http.Error(w, http.StatusText(500), 500)
}

产生 404 的新代码

func serveTemplate(w http.ResponseWriter, r *http.Request, _ 
    httprouter.Params) {
    lp := filepath.Join("templates", "layout.html")
    fp := filepath.Join("templates", filepath.Clean(r.URL.Path))
    gh := filepath.Join("templates", "INC_Header.go.html")
    gn := filepath.Join("templates", "INC_Nav.go.html")
    gf := filepath.Join("templates", "INC_Footer.go.html")
    //log.Println(`enter code here`r.URL.Path)

    tmpl, err := template.ParseFiles(lp, fp, gh, gn, gf)
    if err := tmpl.ExecuteTemplate(w, "layout", nil); err != nil {
        log.Println(err.Error())
        http.Error(w, http.StatusText(500), 500)
   }

最佳答案

评论回复后修改。我看了https://play.golang.org/p/iHUqZQQcv3

您有以下问题:

  1. 路由器处理程序注册问题 r.GET("/tstats/", serveTemplate) - 它只会匹配 http://localhost:8080/tstats/ 其余的一切是 404
    • 例如:404 -> http://localhost:8080/tstats/myfile1.html
  2. 计算模板路径文件的方式filepath.Join("templates", filepath.Clean(r.URL.Path))

老实说,很难猜测您是如何规划/设计您的应用程序的。无论如何-

像下面这样更新你的代码:

  • 更改路由器映射中的/tstats/ => /tstats/*tmpl
  • 更改 fp := filepath.Join("templates", filepath.Clean(r.URL.Path)) => fp := filepath.Join("templates", "tstats", params.ByName("tmpl"))

现在,对于请求 http://localhost:8080/tstats/myfile1.html .它将在此处查找模板 templates/tstats/myfile1.html


(这是最初的回应)

似乎 HandlerFunc 注册问题导致了 404。

我已经根据您的代码创建了示例,您可以试试 https://play.golang.org/p/6ilS0htj-I

顺便说一句,我相信;在您的第一个示例代码中,未使用 func init 中的 tpl 变量。因为您在 serveTemplate 中有同名的局部变量。

关于golang 模板不适用于 httprouter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44536284/

有关golang 模板不适用于 httprouter的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  3. Ruby Sinatra 配置用于生产和开发 - 2

    我已经在Sinatra上创建了应用程序,它代表了一个简单的API。我想在生产和开发上进行部署。我想在部署时选择,是开发还是生产,一些方法的逻辑应该改变,这取决于部署类型。是否有任何想法,如何完成以及解决此问题的一些示例。例子:我有代码get'/api/test'doreturn"Itisdev"end但是在部署到生产环境之后我想在运行/api/test之后看到ItisPROD如何实现? 最佳答案 根据SinatraDocumentation:EnvironmentscanbesetthroughtheRACK_ENVenvironm

  4. ruby - inverse_of 是否适用于 has_many? - 2

    当我使用has_one时,它​​工作得很好,但在has_many上却不行。在这里您可以看到object_id不同,因为它运行了另一个SQL来再次获取它。ruby-1.9.2-p290:001>e=Employee.create(name:'rafael',active:false)ruby-1.9.2-p290:002>b=Badge.create(number:1,employee:e)ruby-1.9.2-p290:003>a=Address.create(street:"123MarketSt",city:"SanDiego",employee:e)ruby-1.9.2-p290

  5. ruby-on-rails - Mandrill API 模板 - 2

    我正在使用Mandrill的RubyAPIGem并使用以下简单的测试模板:testastic按照Heroku指南中的示例,我有以下Ruby代码:require'mandrill'm=Mandrill::API.newrendered=m.templates.render'test-template',[{:header=>'someheadertext',:main_section=>'Themaincontentblock',:footer=>'asdf'}]mail(:to=>"JaysonLane",:subject=>"TestEmail")do|format|format.h

  6. ruby - Chef Ruby 遍历 .erb 模板文件中的属性 - 2

    所以这可能有点令人困惑,但请耐心等待。简而言之,我想遍历具有特定键值的所有属性,然后如果值不为空,则将它们插入到模板中。这是我的代码:属性:#===DefaultfileConfigurations#default['elasticsearch']['default']['ES_USER']=''default['elasticsearch']['default']['ES_GROUP']=''default['elasticsearch']['default']['ES_HEAP_SIZE']=''default['elasticsearch']['default']['MAX_OP

  7. ruby - "undefined method"用于 rails 模型 - 2

    我正在使用带有Rails的Devise,我想添加一个方法“getAllComments”,所以我这样写:classUser在我的Controller中:defdashboard@user=current_user@comments=@user.getAllComments();end当我访问我的url时,我得到了undefinedmethod`getAllComments'for#我做错了什么?谢谢 最佳答案 因为getAllComments是一个类方法,而您正试图将其作为实例方法访问。您要么需要访问它:User.getAllCom

  8. Ruby on Rails regexp equals-tilde 与 array include 用于检查选项列表 - 2

    我正在使用Rails3.2.3和Ruby1.9.3p0。我发现我经常需要确定某个字符串是否出现在选项列表中。看来我可以使用Ruby数组.includemethod:或正则表达式equals-tildematchshorthand用竖线分隔选项:就性能而言,一个比另一个好吗?还有更好的方法吗? 最佳答案 总结:Array#include?包含String元素,在接受和拒绝输入时均胜出,对于您的示例只有三个可接受的值。对于要检查的更大的集合,看起来Set#include?和String元素可能会获胜。如何测试我们应该根据经验对此进行测试

  9. ruby-on-rails - Ruby "Undefined Method"用于类方法 - 2

    Ruby初学者努力简单地将这个@@people散列的值打印到控制台classPerson#haveafirst_nameandlast_nameattributewithpublicaccessorsattr_accessor:first_nameattr_accessor:last_name#haveaclassattributecalled`people`thatholdsanarrayofobjects@@people=[]#havean`initialize`methodtoinitializeeachinstancedefinitialize(first_name,last_

  10. python - 用于 Python 或 Ruby 的 Amazon Book API? - 2

    这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:AmazonAPIlibraryforPython?我正在寻找一个AmazonAPI,它可以让我:按书名或作者查找书籍显示书籍封面获取有关每本书的信息(价格、评级、评论数、格式、页数等)Python或Ruby库都可以(我只想要最容易使用的库)。有什么建议么?我知道在SO上还有其他一些关于此的帖子,但这些API似乎很快就过时了。[几个月前我尝试了几个建议的Ruby库,但无法让它们中的任何一个工作。]

随机推荐