最近,由于热情洋溢的评论,我已经从golang /http转移到了fasthttp。
如您所知,fasthttp不使用(w http.ResponseWriter),而只使用一种语法,即(ctx *fasthttp.RequestCtx)。
我试过使用ctx.Write,但没有成功。
那么,如何在下面的代码中实现http.ResponseWriter来导出我的html模板呢?也请给出一些解释,以便我们大家都能受益。
非常感谢你的帮助!
package main()
import (
"html/template"
"fmt"
"github.com/valyala/fasthttp"
)
type PageData struct {
Title string
}
func init() {
tpl = template.Must(template.ParseGlob("public/templates/*.html"))
}
m := func(ctx *fasthttp.RequestCtx) {
switch string(ctx.Path()) {
case "/":
idx(ctx)
default:
ctx.Error("not found", fasthttp.StatusNotFound)
}
}
fasthttp.ListenAndServe(":8081", m)
}
func idx(ctx *fasthttp.RequestCtx) {
pd := new(PageData)
pd.Title = "Index Page"
err := tpl.ExecuteTemplate(ctx.write, "index.html", pd)
if err != nil {
log.Println("LOGGED", err)
http.Error(ctx.write, "Internal server error", http.StatusInternalServerError)
return
}
}
发布于 2018-01-12 21:36:00
*fasthttp.RequestCtx
实现io.Writer
接口(这就是ctx.Write()
存在的原因),这意味着您可以简单地将ctx
作为参数传递给ExecuteTemplate()
tpl.ExecuteTemplate(ctx, "index.html", pd)
而且,http.Error()
调用将无法工作,因为RequestCtx
不是http.ResponseWriter
。使用RequestCtx
的自己的误差函数代替:
ctx.Error("Internal server error", http.StatusInternalServerError)
https://stackoverflow.com/questions/48234198
复制相似问题