我试图弄清楚是否有可能在编程Web应用程序时不必在所有地方都传递http.ResponseWriter。我正在建立一个简单的mvc Web框架,当不得不使用最后一个函数时,我不得不通过各种函数传递http.ResponseWriter。路线套餐// Struct containing http requests and variablestype UrlInfo struct { Res http.ResponseWriter Req *http.Request Vars map[string]string}func HandleFunc(handlepath string, runfunc func(*UrlInfo)) { // Set handler and setup struct http.HandleFunc(getHandlePath(handlepath), func(w http.ResponseWriter, r *http.Request) { url := new(UrlInfo) url.Res = w url.Req = r url.Vars = parsePathVars(r.URL.Path, handlepath) runfunc(url) })}// Parse file and send to responsewriterfunc View(w http.ResponseWriter, path string, data interface{}) { // Go grab file from views folder temp, err := template.ParseFiles(path+".html") if err != nil { // Couldnt find html file send error http.Error(w, err.Error(), http.StatusInternalServerError) } else { temp.ExecuteTemplate(w, temp.Name(), data) }}控制器包装import ( "routes")func init() { // Build handlefunc routes.HandleFunc("/home/", home)}func home(urlinfo *routes.UrlInfo) { info := make(map[string]string) info["Title"] = urlinfo.Vars["title"] info["Body"] = "Body Info" gi.View(urlinfo.Res, "pages/about", info)}我不想不必在home函数中传递任何内容,因此我可以再次将其传递给view函数以吐出。能够将其设置在一个位置并在需要时从中拉出会很高兴。对于在相同方面与路由程序包通信的多个程序包,这也很好。欢迎任何想法,技巧或窍门。谢谢。
1 回答
- 1 回答
- 0 关注
- 753 浏览
添加回答
举报
0/150
提交
取消