本篇文章為大家展示了golang微服務(wù)框架中如何擴展go-zero使之支持html模板解析自動化,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
成都創(chuàng)新互聯(lián)網(wǎng)站建設(shè)公司提供網(wǎng)站設(shè)計和自適應(yīng)建站服務(wù)。團隊由有經(jīng)驗的網(wǎng)頁設(shè)計師、程序員和市場專家組成,能夠提供從H5網(wǎng)站設(shè)計,網(wǎng)站制作,一元廣告,模板建站到重慶小程序開發(fā)公司等全方位服務(wù)。 以客戶為中心,致力于為客戶提供創(chuàng)新、高效的解決方案,幫助您打造成功的企業(yè)網(wǎng)站。
go-zero本身支持html模板解析,我們只需要添加url對應(yīng)模板解hanlder,實現(xiàn)邏輯就可以了
不寫任何一個和模板相關(guān)的handler
如果有新的模板,直接把模板到某個特定目錄就好,不要動任何go代碼
在開發(fā)環(huán)境下沒有緩存,修改了模板文件無需重啟
需求在這里,開擼吧
金光燦燦的Gorm V2+適合創(chuàng)業(yè)的golang微服務(wù)框架go-zero實戰(zhàn) 如果對go-zero已經(jīng)了解,直接跳過吧
以如下指令創(chuàng)建項目
mkdir html cd html go mod init html
本文設(shè)計API如下 |描述|格式|方法|參數(shù)|返回|是否需要鑒權(quán)| |----|----|----|----|----|----| |用戶登錄|/open/authorization|post|mobile:手機號,passwd:密碼,code:圖片驗證碼|id:用戶ID,token:用戶token|否|
根據(jù)以上描述,書寫api的模板文件如下
type ( UserOptReq struct { mobile string `form:"mobile"` passwd string `form:"passwd"` code string `form:"code,optional"` } UserOptResp struct { id uint `json:"id"` token string `json:"token"` } ) service html-api { @server( handler: authorizationHandler folder: open ) post /open/authorization(UserOptReq) returns(UserOptResp) }
注意
本文和html模板相關(guān),可以不適用goctl工具
但是由于使用工具可以為我們節(jié)省很多搭建框架相關(guān)的工作,所以建議使用用ctl生成
采用如下指令生成代碼
goctl api go -api html.api -dir .
此時用go run html.go
指令可以發(fā)現(xiàn)系統(tǒng)以及運行
模板解析需要了解如下倆個已知知識點
html網(wǎng)頁輸出本質(zhì)上是get請求輸出
相對于一個項目來說,模板文件個數(shù)是有限的,因此我們可以將模板枚舉出來,完成訪模板名稱和請求之間的映射
對于第一個,我們可以構(gòu)建get路由來實現(xiàn)請求,以首頁請求http://127.0.0.1:8888/index.html
為例,核心代碼如下,
htmltplrouter:= rest.Route{ Method: http.MethodGet, Path: "/index.html", Handler: htmlhandler(...), } engine.AddRoute(htmltplrouter)
在上述代碼中,htmlhandler
函數(shù)實現(xiàn)了對請求的響應(yīng),也就是解析了模板并將模板內(nèi)容輸出
//gloabtemplate:全局解析的模板參數(shù) //tplname:模板名稱, //serverCtx 應(yīng)用配置 func htmlhandler(gloabtemplate *template.Template, tplname string, serverCtx *svc.ServiceContext) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { //模板名字就是r.URL.Path t := gloabtemplate //如果是調(diào)試模式,則支持熱解析 if serverCtx.Config.Debug { t, _ = template.New("").Funcs(FuncMap()).ParseGlob(serverCtx.Config.TemplatePattern) } err := t.ExecuteTemplate(w, tplname, r.URL.Query()) if err != nil { httpx.Error(w, err) } } }
這里有幾個點需要強調(diào):
在golang中,每個包含模板內(nèi)容的html文件會被解析成一個模板,如在view/www/
下新建test.html
文件,即使里面沒有內(nèi)容,系統(tǒng)也會將其解析得到一個名叫test.html
的模板。
如果在模板文件以template標(biāo)簽中定義名稱為www/test.html
的模板,則系統(tǒng)又會解析得到一個名叫www/test.html
的模板,此時存在倆個模板,一個名叫test.html
,一個名叫www/test.html
view/www/test.html
文件內(nèi)容如下
{{define "www/test.html"}} <h2>這是模板www/test.html的內(nèi)容</h2> {{end}}
因此我們可以取巧,將模板名稱命名成需要建立映射關(guān)系的uri 比如外部通過http://127.0.0.1:8888/www/test.html
來訪問,此時req.URI.path為/www/test.html
我們可以用這個作為模板名稱
這里用到了ParseGlob
函數(shù),這個函數(shù)本質(zhì)上是對filepath.ParseGlob()
和template.ParseFiles()
的封裝,可以遍歷滿足一定格式的路徑的所有文件,假設(shè)我們建立模板存放目錄internal\view
如下
tree /F /A | go.mod | go.sum | html.api | html.go | readme.md | +---etc | html-api.yaml | \---internal +---config | config.go | +---handler | | routes.go | | | \---open | authorizationhandler.go | +---logic | \---open | authorizationlogic.go | +---svc | servicecontext.go | +---types | types.go | \---view +---public | footer.html | header.html | \---www index.html test.html
則我們可以使用格式字符串 ./internal/view/**/*
來遍歷并解析并解析模板,建立模板和uri之間的對應(yīng)關(guān)系,核心代碼如下
gloabtemplate,err:=template.New("").Funcs(FuncMap()).ParseGlob("./internal/view/**/*") //range輪詢 for _, tpl := range gloabtemplate.Templates() { patern := tpl.Name() if !strings.HasPrefix(patern, "/") { patern = "/" + patern } //首頁默認(rèn)index.html index.htm index.php tplname := tpl.Name() if 0 == len(tplname) { tplname = serverCtx.Config.TemplateIndex } pageRouters = append(pageRouters, rest.Route{ Method: http.MethodGet, Path: patern, Handler: htmlhandler(gloabtemplate, tplname, serverCtx), }) logx.Infof("register page %s %s", patern, tplname) } //添加到engin路由中 engine.AddRoutes(pageRouters)
有時候我們需要在模板中使用函數(shù),則需要用到函數(shù)映射功能,golang提供接口函數(shù)Funcs()
來注入,
假設(shè)我們需要在/www/version.html中查看系統(tǒng)版本,應(yīng)該怎么做呢?
定義相關(guān)函數(shù)
//handlers\funcs.go package handler import ( "html/template" ) //定義 var funcsMap template.FuncMap = make(template.FuncMap) func FuncMap() template.FuncMap { funcsMap["version"] = version funcsMap["hello"] = hello return funcsMap } func version() string { //這個函數(shù)返回當(dāng)前版本號0.0.1 return "0.01" } func hello(str string) string { //這個函數(shù)返回當(dāng)前版本號0.0.1 return "hello "+ str }
應(yīng)用可以通過 template.New("").Funcs(FuncMap())
來注入響應(yīng)函數(shù)
定義模板文件 新建文件view/www/version.html
,內(nèi)容如下
{{define "www/version.html"}} <h2>當(dāng)前版本號:{{version}}</h2> <h2>這里測試帶參數(shù)的函數(shù):{{hello "word"}}</h2> {{end}}
無參數(shù)的函數(shù)展示 此時模板文件中通過 {{version}}
即可調(diào)用并顯示版本號0.01
有參數(shù)的函數(shù) 對應(yīng)有參數(shù)的函數(shù),按照參數(shù)順序排列,中間用空格隔開
以上顯示結(jié)果
當(dāng)前版本號:0.01 這里測試帶參數(shù)的函數(shù):hello word
使用templete
指令進行嵌套
新建view/public/header.html
內(nèi)容如下
<!-- 頂部菜單 Start --> <div class="top-menu-wrapper index-menu"> <h2>這是Head</h2> </div>
新建view/public/footer.html
內(nèi)容如下
<!-- 頂部菜單 Start --> <div class="top-menu-wrapper index-menu"> <h2>這是footer</h2> </div>
新建view/www/index.html
文件,內(nèi)容如下
<!DOCTYPE html> <html> <head></head> <body> {{template "header.html" .}} <div class="content-box" data-spy="scroll" data-target=".section-scrollspy"> <h2>這是Index的內(nèi)容</h2> </div> {{template "footer.html" .}} </body> </html>
此時編譯后即可得到如下內(nèi)容
這是Head 這是Index的內(nèi)容 這是footer
在模板中直接使用 首先需要將變量暴露到模板中,這里我們使用到了ExecuteTemplate
函數(shù),該函數(shù)第三個參數(shù)即可以在模板里面訪問的參數(shù),比如如下代碼,則在模板中可以訪問Query了
data := r.URI.Query err := t.ExecuteTemplate(w, tplname, data)
新建view/www/arg.html
文件
{{define "www/arg.html"}} <h6>arga={{.arga}}</h6> <h6>argb={{.argb}}</h6> {{end}}
請求訪問方式http://127.0.0.1:8888/www/arg.html?arga=123&argb=456
系統(tǒng)返回結(jié)果
arga=[123] argb=[456]
在嵌套模板中使用
在嵌套模板中使用需要將對象傳入,方式是在模板名后加一個.
,如下 新建view/www/embd.html
文件
{{define "www/embd.html"}} 沒加點:{{template "www/arg.html"}} ======= 加點:{{template "www/arg.html" .}} {{end}}
結(jié)果如下
沒加點: <h6>arga=</h6> <h6>argb=</h6> ======= 加點: <h6>arga=[123]</h6> <h6>argb=[456]</h6>
假設(shè)我們的應(yīng)用支持開發(fā)模式和生產(chǎn)模式,在生產(chǎn)模式下,由于有性能考慮,系統(tǒng)不需要每次訪問都解析模板。而在開發(fā)模式下,每個模板有所任何小的修改,我們都希望模板能自動更新,怎么實現(xiàn)這個功能呢? 方案很多,有文件監(jiān)聽方案,如github.com/fsnotify/fsnotify
監(jiān)聽模板目錄,也有標(biāo)記位方案,無論模板有沒有變動,只要是開發(fā)模式,每次請求都重新加載模板并解析,gin
就是這種方案,本文也采用這種方案,核心代碼如下
//模板名字就是r.URL.Path t := gloabtemplate //如果是debug模式 if serverCtx.Config.Debug { //每次都重新解析 t, _ = template.New("").Funcs(FuncMap()).ParseGlob(serverCtx.Config.TemplatePattern) } err := t.ExecuteTemplate(w, tplname, r.URL.Query())
本質(zhì)上是指定/
請求對應(yīng)的模板,以及系統(tǒng)錯誤對應(yīng)的模板
for _, tpl := range gloabtemplate.Templates() { patern := tpl.Name() if !strings.HasPrefix(patern, "/") { patern = "/" + patern } //處理首頁邏輯 tplname := tpl.Name() if 0 == len(tplname) { //模板名稱為""那么就默認(rèn)首頁吧 //恰好/對應(yīng)的模板名稱為"", tplname = serverCtx.Config.TemplateIndex } pageRouters = append(pageRouters, rest.Route{ Method: http.MethodGet, Path: patern, Handler: htmlhandler(gloabtemplate, tplname, serverCtx), }) logx.Infof("register page %s %s", patern, tplname) }
目前可以實現(xiàn)業(yè)務(wù)邏輯層面的404定制,如httpx.Error方法可用404.html替代。 對于部分場景如訪問一個不存在的url,則需要go-zero
官方提供支持,并開發(fā)接口。
以上操作完成后,我們得到如下項目目錄,
tree /F /A | go.mod | go.sum | html.api | html.go | readme.md | +---etc | html-api.yaml | \---internal +---config | config.go | +---handler | | funcs.go | | html.go | | routes.go | | | \---open | authorizationhandler.go | +---logic | \---open | authorizationlogic.go | +---svc | servicecontext.go | +---types | types.go | \---view +---public | 404.html | footer.html | header.html | \---www arg.html embd.html func.html index.html test.html
在routes.go
中添加如下代碼段即可
func RegisterHandlers(engine *rest.Server, serverCtx *svc.ServiceContext) { engine.AddRoutes([]rest.Route{ { Method: http.MethodPost, Path: "/open/authorization", Handler: open.AuthorizationHandler(serverCtx), }, }) //添加這個代碼段 RegisterHtmlHandlers(engine, serverCtx) }
關(guān)注公眾號betaidea
輸入html
即可獲得html解析相關(guān)代碼 關(guān)注公眾號betaidea
輸入jwt
即可獲得gozero集成jwt-token相關(guān)代碼 關(guān)注公眾號betaidea
輸入gozero
即可gozero入門代碼
目前貌似還沒找到go-zero對static file支持的例子,類似gin
哪樣做靜態(tài)資源服務(wù)貌的例子,那么明天就寫一個吧。 在go-zero的路由框架下尋找解決方案。 《用go-zero 支持文件服務(wù)》
送福利了uniapp用戶福音來啦! 歷經(jīng)數(shù)十萬用戶考驗,我們的客服系統(tǒng)終于對外提供服務(wù)了。 你還在為商城接入客服煩惱嗎?只需一行代碼,即可接入啦!! 只需一行代碼!!!!
/*kefu.vue*/ <template> <view> <IdeaKefu :siteid="siteId" ></IdeaKefu> </view> </template> <script> import IdeaKefu from "@/components/idea-kefu/idea-kefu.vue" export default { components:{ IdeaKefu }, data() { return { siteId:2 } } }
效果杠杠的
上述內(nèi)容就是golang微服務(wù)框架中如何擴展go-zero使之支持html模板解析自動化,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
當(dāng)前題目:golang微服務(wù)框架中如何擴展go-zero使之支持html模板解析自動化
分享URL:http://aaarwkj.com/article44/jjgjee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站收錄、App設(shè)計、響應(yīng)式網(wǎng)站、App開發(fā)、電子商務(wù)、定制網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)