jjzjj

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

coder 2024-07-11 原文

我希望在 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/

有关url - Golang 提供主页并提供模板页面的更多相关文章

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

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

  2. ruby-on-rails - rails : save file from URL and save it to Amazon S3 - 2

    从给定URL下载文件并立即将其上传到AmazonS3的更直接的方法是什么(+将有关文件的一些信息保存到数据库中,例如名称、大小等)?现在,我既不使用Paperclip,也不使用Carrierwave。谢谢 最佳答案 简单明了:require'open-uri'require's3'amazon=S3::Service.new(access_key_id:'KEY',secret_access_key:'KEY')bucket=amazon.buckets.find('image_storage')url='http://www.ex

  3. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

  4. ruby-on-rails - Ruby url 到 html 链接转换 - 2

    我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.

  5. ruby-on-rails - 如何生成传递一些自定义参数的 `link_to` URL? - 2

    我正在使用RubyonRails3.0.9,我想生成一个传递一些自定义参数的link_toURL。也就是说,有一个articles_path(www.my_web_site_name.com/articles)我想生成如下内容:link_to'Samplelinktitle',...#HereIshouldimplementthecode#=>'http://www.my_web_site_name.com/articles?param1=value1¶m2=value2&...我如何编写link_to语句“alàRubyonRailsWay”以实现该目的?如果我想通过传递一些

  6. ruby - Rack:如何将 URL 存储为变量? - 2

    我正在编写一个简单的静态Rack应用程序。查看下面的config.ru代码:useRack::Static,:urls=>["/elements","/img","/pages","/users","/css","/js"],:root=>"archive"map'/'dorunProc.new{|env|[200,{'Content-Type'=>'text/html','Cache-Control'=>'public,max-age=6400'},File.open('archive/splash.html',File::RDONLY)]}endmap'/pages/search.

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

  8. ruby-on-rails - Rails - 使用/自定义 URL : '/dashboard' 指定根路径 - 2

    如何使此根路径转到:“/dashboard”而不仅仅是http://example.com?root:to=>'dashboard#index',:constraints=>lambda{|req|!req.session[:user_id].blank?} 最佳答案 您可以通过以下方式实现:root:to=>redirect('/dashboard')match'/dashboard',:to=>"dashboard#index",:constraints=>lambda{|req|!req.session[:user_id].b

  9. 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

  10. ruby - 在 ASP 页面上 Mechanize 中断 - 2

    require'mechanize'agent=Mechanize.newlogin=agent.get('http://www.schoolnet.ch/DE/HomeDE.htm')agent.clicklogin.link_withtext:/Login/然后我得到Mechanize::UnsupportedSchemeError。 最佳答案 Mechanize不支持javascript但您可以将搜索字段添加到表单并为其分配搜索词并使用mechanize提交表单form=page.forms.firstform.add_fie

随机推荐