教你如何搭建自己的go-gin框架(六) 模板处理

18211167516 · · 1455 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

## 引言 > 简单说下本章的重点 * 1、静态服务器支持(映射静态文件路由) * 2、模板渲染 * 3、[代码地址 https://github.com/18211167516/go-Ebb/tree/master/day6-template](https://github.com/18211167516/go-Ebb/tree/master/day6-template) ## 1、支持静态服务器 ```golang func (group *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc { absolutePath := joinPaths(group.prefix, relativePath) fileServer := http.StripPrefix(absolutePath, http.FileServer(fs)) return func(c *Context) { file := c.Param("filepath") // Check if file exists and/or if we have permission to access it f, err := fs.Open(file); defer f.Close() if err != nil { c.Status(http.StatusNotFound) return } fileServer.ServeHTTP(c.Writer, c.Request) } } // serve static files func (group *RouterGroup) Static(relativePath string, root string) { handler := group.createStaticHandler(relativePath, http.Dir(root)) urlPattern := joinPaths(relativePath, "/*filepath") // Register GET handlers group.GET(urlPattern, handler) } func joinPaths(absolutePath, relativePath string) string { if relativePath == "" { return absolutePath } finalPath := path.Join(absolutePath, relativePath) return finalPath } ``` ## 2、单元测试 ```golang func TestStaticFile(t *testing.T){ r := Default() r.Static("/assets", "./") w := PerformRequest("GET","/assets/go.mod",bytes.NewBufferString(""),r) fmt.Printf(w.Body.String()) } ``` ## 3、模板渲染 ```golang type Engine struct{ *RouterGroup //v4新增 顶级路由组 router *router groups []*RouterGroup // v4新增 //html/template HTMLRender *template.Template HTMLdelimsLeft string HTMLdelimsRight string funcMap template.FuncMap } func (engine *Engine) SetFuncMap(funcName string,f interface{}) { funcMap := template.FuncMap{ funcName: f, } engine.funcMap = funcMap } func (engine *Engine) LoadHTMLGlob(pattern string) { engine.HTMLdelimsLeft = "{" engine.HTMLdelimsRight= "}" engine.HTMLRender = template.Must(template.New("").Delims(engine.HTMLdelimsLeft,engine.HTMLdelimsRight).Funcs(engine.funcMap).ParseGlob(pattern)) } func (engine *Engine) ServeHTTP(w http.ResponseWriter,req *http.Request){ c := newContext(w, req) c.engine = engine //新增 engine.handleHTTPRequest(c) } ``` ## 4、改造Context HTML方法 ```golang func (c *Context) HTML(code int,TmpName string,data interface{}){ c.SetHeader("Content-Type", "text/html") c.Status(code) if err := c.engine.HTMLRender.ExecuteTemplate(c.Writer, TmpName, data); err != nil { c.JSON(500, err.Error()) } } ``` ## 5、demo ```golang package main import ( "ebb" "time" "fmt" ) type student struct { Name string Age int8 } func FormatDate(t time.Time) string { year, month, day := t.Date() Hour,Minute,Second := t.Hour(),t.Minute(),t.Second() return fmt.Sprintf("%d-%02d-%02d %d:%d:%d", year, month, day,Hour,Minute,Second) } func main(){ r := ebb.Default() r.GET("/panic",func(c *ebb.Context) { panic("err") }) r.POST("/login/*name",func(c *ebb.Context) { c.JSON(200, ebb.H{ "name": c.Param("name"), }) }) r.Static("/assets", "./static") r.SetFuncMap("formatDate",FormatDate) r.LoadHTMLGlob("templates/*") stu1 := &student{Name: "Geektutu", Age: 20} stu2 := &student{Name: "Jack", Age: 22} r.GET("/students", func(c *ebb.Context) { c.HTML(200, "students.tmpl", ebb.H{ "title": "ebb students", "now": time.Now(), "stuArr": [2]*student{stu1, stu2}, }) }) r.Run(":8080") } ``` ```html <html> <body> <p>hello, {.title}</p> <p>now : {.now |formatDate}</p> {range $index, $ele := .stuArr } <p>{ $index }: { $ele.Name } is { $ele.Age } years old</p> { end } </body> </html> ``` > 自此带着大家搭建gin已经完结,希望大家有所收获,不白看,多动手

有疑问加站长微信联系(非本文作者))

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

1455 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传