Skip to content

Commit

Permalink
feat:模板相关方法
Browse files Browse the repository at this point in the history
  • Loading branch information
convee committed Feb 22, 2023
1 parent f89d69f commit e4aa311
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 13 deletions.
28 changes: 19 additions & 9 deletions art.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package artgo

import (
"html/template"
"net/http"
"path"
"strings"
Expand All @@ -10,8 +11,10 @@ type HandlerFunc func(*Context)

type Engine struct {
*RouterGroup
router *router
routerGroups []*RouterGroup
router *router
routerGroups []*RouterGroup
htmlTemplates *template.Template
funcMap template.FuncMap
}

type RouterGroup struct {
Expand Down Expand Up @@ -54,15 +57,17 @@ func (g *RouterGroup) addRoute(method string, comp string, handler HandlerFunc)
g.engine.router.addRoute(method, pattern, handler)
}

//GET 将 GET 路由加载到内存
func (g *RouterGroup) GET(pattern string, handler HandlerFunc) {
g.addRoute("GET", pattern, handler)
}

//POST 将 POST 路由加载到内存
func (g *RouterGroup) POST(pattern string, handler HandlerFunc) {
g.addRoute("POST", pattern, handler)
}

// create static handler
// createStaticHandler 创建静态文件 handler
func (g *RouterGroup) createStaticHandler(relativePath string, fs http.FileSystem) HandlerFunc {
absolutePath := path.Join(g.name, relativePath)
fileServer := http.StripPrefix(absolutePath, http.FileServer(fs))
Expand All @@ -78,21 +83,25 @@ func (g *RouterGroup) createStaticHandler(relativePath string, fs http.FileSyste
}
}

// serve static files
// Static 静态文件服务
func (g *RouterGroup) Static(relativePath string, root string) {
handler := g.createStaticHandler(relativePath, http.Dir(root))
urlPattern := path.Join(relativePath, "/*filepath")
// Register GET handlers
g.GET(urlPattern, handler)
}

func (g *RouterGroup) StaticFs(pattern, path, dir string) {
handler := func(c *Context) {
http.StripPrefix(path, http.FileServer(http.Dir(dir))).ServeHTTP(c.Writer, c.Req)
}
g.addRoute("GET", pattern, handler)
// SetFuncMap 渲染自定义模板
func (e *Engine) SetFuncMap(funcMap template.FuncMap) {
e.funcMap = funcMap
}

// LoadHTMLGlob 加载模板到内存
func (e *Engine) LoadHTMLGlob(pattern string) {
e.htmlTemplates = template.Must(template.New("").Funcs(e.funcMap).ParseGlob(pattern))
}

// ServeHTTP 实现 http.Handler 接口
func (e *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
var middlewares []HandlerFunc
for _, group := range e.routerGroups {
Expand All @@ -106,6 +115,7 @@ func (e *Engine) ServeHTTP(w http.ResponseWriter, req *http.Request) {
e.router.handle(c)
}

// Run 启动自定义 http 服务器
func (e *Engine) Run(addr string) (err error) {
return http.ListenAndServe(addr, e)
}
15 changes: 13 additions & 2 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,34 +39,41 @@ func (c *Context) Next() {
}
}

// Param 获取路由参数
func (c *Context) Param(key string) string {
value, _ := c.Params[key]
return value
}

// PostForm 获取 POST 参数
func (c *Context) PostForm(key string) string {
return c.Req.FormValue(key)
}

// Query 获取 GET 参数
func (c *Context) Query(key string) string {
return c.Req.URL.Query().Get(key)
}

// Status 设置响应状态码
func (c *Context) Status(code int) {
c.StatusCode = code
c.Writer.WriteHeader(code)
}

// SetHeader 设置响应头
func (c *Context) SetHeader(key string, value string) {
c.Writer.Header().Set(key, value)
}

// String 返回格式化字符串
func (c *Context) String(code int, format string, values ...interface{}) {
c.SetHeader("Content-Type", "text/plain")
c.Status(code)
_, _ = c.Writer.Write([]byte(fmt.Sprintf(format, values...)))
}

// JSON 返回 json 数据
func (c *Context) JSON(code int, obj interface{}) {
c.SetHeader("Content-Type", "application/json")
c.Status(code)
Expand All @@ -76,16 +83,19 @@ func (c *Context) JSON(code int, obj interface{}) {
}
}

// Data 返回文本数据
func (c *Context) Data(code int, data []byte) {
c.Status(code)
_, _ = c.Writer.Write(data)
}

// HTML 输出 html
func (c *Context) HTML(code int, html string) {
func (c *Context) HTML(code int, name string, data interface{}) {
c.SetHeader("Content-Type", "text/html")
c.Status(code)
_, _ = c.Writer.Write([]byte(html))
if err := c.engine.htmlTemplates.ExecuteTemplate(c.Writer, name, data); err != nil {
c.Error(http.StatusInternalServerError, err.Error())
}
}

// Redirect 重定向
Expand All @@ -103,6 +113,7 @@ func (c *Context) SetCookie(cookie *http.Cookie) {
http.SetCookie(c.Writer, cookie)
}

// Render 渲染模板
func (c *Context) Render(data interface{}, filenames ...string) error {
t, err := template.ParseFiles(filenames...)
if err != nil {
Expand Down
5 changes: 3 additions & 2 deletions trie.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
package artgo

import (
"fmt"
"strings"
Expand Down Expand Up @@ -51,7 +52,7 @@ func (n *node) search(parts []string, height int) *node {
return nil
}

func (n *node) travel(list *([]*node)) {
func (n *node) travel(list *[]*node) {
if n.pattern != "" {
*list = append(*list, n)
}
Expand All @@ -77,4 +78,4 @@ func (n *node) matchChildren(part string) []*node {
}
}
return nodes
}
}

0 comments on commit e4aa311

Please sign in to comment.