dongzu3511 2017-03-10 20:07
浏览 57
已采纳

转到:根据错误代码加载模板

I would like to Execute a different template based on a http error code.

I was thinking to use template.ParseFiles(), but I am confused how to do this dynamically. In fact, ParseFiles() can load an array of strings (filenames).

Do I have to ParseFiles() for every file individually, in order to assign its result to an error code in a map? If I ParseFiles() all into an array, how can I then assign each of the templates to the error code?

I would like to avoid having to ParseFiles() on each request, I would prefer to do the parsing in init() and Execute only on request.

Here's what I have so far (does not compile yet):

package main

import (
    "os"
    "html/template"
    "net/http"
)

var templateMap map[int]*template.Template

func init() {
  initErrHandling()
}

func initErrHandling() {

  templateMap = make(map[int]*template.Template)
  templateMap[0]   = "generic.html" //default
  templateMap[400] = "generic.html"
  templateMap[401] = "unauthorized.html"
  templateMap[403] = "forbidden.html"
  templateMap[404] = "notfound.html"
  templateMap[422] = "invalidparams.html"
  templateMap[500] = "generic.html"

  template.ParseFiles() //parseFiles all files in one call, or parseFiles one by one and assign to error code, e.g. templateMap[404],_ = template.parseFiles("notfound.html")? 
}


func getTemplate(code int) (*template.Template) {
  if val, tmpl := templateMap[code]; tmpl {
    return tmpl
  } else {
    return templateMap[0]
  }
}

func showError(w http.ResponseWriter, code int) {
    getTemplate(code).Execute(w)    
} 

func main() {
    showError(os.Stdout, 400)
} 
  • 写回答

1条回答 默认 最新

  • dongpa3109 2017-03-10 20:27
    关注

    Use one map to record the file names and a second map for the parsed templates:

    func initErrHandling() {  // call from init()
      fnames := map[int]string{
        0:   "generic.html", //default
        400: "generic.html",
        401: "unauthorized.html",
        403: "forbidden.html",
        404: "notfound.html",
        422: "invalidparams.html",
        500: "generic.html",
      }
      templateMap = make(map[int]*template.Template)
      for code, fname := range fnames {
        templateMap[code] = template.Must(template.ParseFiles(fname))
      }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案