亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

golang傳遞http.ResponseWriter

golang傳遞http.ResponseWriter

Go
神不在的星期二 2021-05-14 12:13:22
我試圖弄清楚是否有可能在編程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 關注
  • 778 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號