如何使用 http.ResponseWriter in fasthttp for for execute HTML 模板



由于好评如潮,我最近从golang net/http转移到fasthttp。

如你所知,fasthttp不使用(w http。ResponseWriter(,但只有一种语法是(ctx *fasthttp.请求Ctx(。

我尝试使用ctx。写,但没有用。

那么,我该如何实现http。下面的代码中的响应编写器来执行我的 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
}

}

*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)

最新更新