我試圖弄清楚是否有可能在編程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 回答
- 0 關注
- 778 瀏覽
添加回答
舉報
0/150
提交
取消