这里用的goframe v2框架
提醒:下面的import 引入的控制器和api,根据自己实际项目路径
main函数
import ("context""github.com/gogf/gf/v2/net/ghttp""github.com/gzdzh/dzhgo/modules/dzhCms/controller/web""github.com/gogf/gf/v2/frame/g")func main() {s := g.Server()s.Group("/web", func(group *ghttp.RouterGroup) {group.Bind(new(web.CmsIndexController),)})s.Run()
}
中间件全局拦截路由
可以预处理一些事情,例如判断模板不存在的提示语
package middlewareimport ("context""github.com/gogf/gf/v2/frame/g""github.com/gogf/gf/v2/os/gfile"
)func init() {s := g.Server()ctx := context.Background()// 普通静态文件if gfile.Exists("./template") {s.AddStaticPath("/template", "/template")} else {g.Log().Debug(ctx, "/template 不存在,创建一个")if err := gfile.Mkdir("./template"); err != nil {return}}func IndexMiddleware(r *ghttp.Request) {indexHtml := gfile.Exists("./template/index.html")var templateName stringif indexHtml {templateName = "index.html"r.SetParam("templateName", templateName)r.Middleware.Next()return} else {r.Response.Writefln("模板不存在")}}// 预处理首页模版s.BindMiddleware("/web/index", IndexMiddleware)}
接口
package v1import "github.com/gogf/gf/v2/frame/g"type IndexReq struct {g.Meta `path:"/index" method:"GET"`
}
控制器
package webimport ("context""github.com/gzdzh/dzhgo/dzhCore"v1 "github.com/gzdzh/dzhgo/modules/dzhCms/api/v1""github.com/gogf/gf/v2/frame/g""github.com/gogf/gf/v2/os/gview"
)type CmsIndexController struct {}func (c *CmsIndexController) Index(ctx context.Context, req *v1.IndexReq) (res *dzhCore.BaseRes, err error) {view := gview.New()// 设置模板目录err = view.SetPath("template")if err != nil {return nil, err}view.Assigns(map[string]interface{}{"name": "john","age": 18,"score": 100,})// 渲染模板content, err := view.Parse(ctx, "index.html")if err != nil {panic(err)}var r = g.RequestFromCtx(ctx)r.Response.Writefln(content)return
}
前端模板
根目录template的文件夹放模板文件,中间件那里已经映射到该目录了,如果没有该目录,会自动建一个
模板:/template/index.html
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>模板引擎渲染</title>
</head>
<body><p>Name: {{.name}}</p><p>Age: {{.age}}</p><p>Score:{{.score}}</p></body>
</html>
浏览器打开 http://localhost:端口/web/index