下面的代码呈现初始页面,其中有一个表单。在提交该表单时,我想呈现一个结果页面。表单已提交并已处理,但我看到的只是一个空白的 html 文档。
我不想只显示一个 html 页面,而是呈现它,因为一些内容将来 self 提交表单时的 golang 代码。我正在尝试使用模板(来自模板)在指定行中执行此操作<body></body>
是 Golang 变量的值。
如果有人能帮我弄清楚如何呈现结果页面,我将不胜感激。
package main
import (
//"fmt"
"net/http"
"github.com/zenazn/goji"
"github.com/zenazn/goji/web"
"html/template"
"io/ioutil"
)
type Page struct {
Title string
Body []byte
}
func (p *Page) save() error{
filename := p.Title + ".txt"
return ioutil.WriteFile(filename, p.Body, 0600)
}
func loadPage(title string) (*Page, error){
filename := title + ".txt"
body, err := ioutil.ReadFile(filename)
if err != nil{
return nil, err
}
return &Page{Title: title, Body: body}, nil
}
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page){
t, _ := template.ParseFiles("Projects/Go/src/web/site/" + tmpl + ".html")
t.Execute(w, p)
}
func editHandler(w http.ResponseWriter, r *http.Request){
title := r.URL.Path[len("/edit/"):]
p, err := loadPage(title)
if err != nil{
p = &Page{Title: title}
}
renderTemplate(w, "edit", p)
}
func viewHandler(w http.ResponseWriter, r *http.Request){
title := r.URL.Path[len("/ask"):]
p, _ := loadPage(title)
renderTemplate(w, "ask", p)
}
func response(c web.C, w http.ResponseWriter, r *http.Request){
//name := r.FormValue("name")
//fmt.Fprintf(w, "Hello, %s!", name)
http.HandleFunc("/ask", viewHandler)
http.HandleFunc("/edit/", editHandler)
//http.HandleFunc("/save", saveHandler)
http.ListenAndServe("8000", nil)
}
func serveSingle(filename string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, filename)
}
}
func main() {
goji.Get("/", serveSingle("Projects/Go/src/web/site/index.html"))
goji.Handle("/ask", response)
goji.Serve()
}
文件结构:
root/Projects/Go/src/web/site/edit.html
root/Projects/Go/src/web/site/index.html
root/Projects/Go/src/web/site/view.html
index.html 的正文:
<form action="ask" method="get">
<input type="text" name="q" />
</form>
view.html 的正文:
<form action="ask" method="get">
<input type="text" name="q" />
</form>
<h1 class="abTitle">{{printf "%s" .Body}}</h1>
view.html 和 edit.html 完全一样。
最佳答案
理论上,您发布的脚本应该对 /
请求做出响应,并在向 /ask
请求时崩溃。在对 /ask
的请求上,它应该执行 response
处理程序和 panic(正如文档指定的 http://golang.org/pkg/net/http/#ServeMux.Handle 但究竟会发生什么还不清楚。无论如何,它会更加惯用(对于这样的小型服务器)提前配置所有处理程序并避免在响应中注册处理程序。
另一个问题是在 viewHandler
函数中——它将仅通过 /ask
请求被调用,但是随后 /ask
将被剥离标题将是“”——这将导致加载“.txt”模板文件,这可能不是故意的。
如果您发布表单模板的内容和文件结构(文件夹和文件名),这也会很有帮助。
关于html - 尝试在提交表单时呈现结果页面时,显示空白 html 文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25457558/