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 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP