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

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

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

}