From 91046f25d1c627c7b89a99eeab9fef4f13579873 Mon Sep 17 00:00:00 2001 From: unknown <352120190@qq.com> Date: Sun, 17 Apr 2022 19:51:59 +0800 Subject: [PATCH] Add Text/HTML/HTMLFromFile function --- framework/context.go | 37 +++++++++++++++++++++++++++++++++---- main.go | 10 ++++++---- 2 files changed, 39 insertions(+), 8 deletions(-) diff --git a/framework/context.go b/framework/context.go index 069da96..8d9e749 100644 --- a/framework/context.go +++ b/framework/context.go @@ -5,10 +5,13 @@ import ( "context" "encoding/json" "errors" + "fmt" "io/ioutil" "net/http" + "path/filepath" "strconv" "sync" + "text/template" "time" ) @@ -255,12 +258,38 @@ func (c *Context) Json(status int, object interface{}) error { return nil } -func (c *Context) HTML(status int, object interface{}, template string) error { - // TODO +func (c *Context) HTML(template_ string, object interface{}) error { + t, err := template.New("output").Parse(template_) + if err != nil { + fmt.Printf("%s\n", err.Error()) + return err + } + if err := t.Execute(c.writer, object); err != nil { + fmt.Printf("%s\n", err.Error()) + return err + } + c.writer.Header().Set("Content-Type", "application/html") + return nil +} + +func (c *Context) HTMLFromFile(filename string, object interface{}) error { + _, fn := filepath.Split(filename) + t, err := template.New(fn).ParseFiles(filename) + if err != nil { + fmt.Printf("%s\n", err.Error()) + return err + } + if err := t.Execute(c.writer, object); err != nil { + fmt.Printf("%s\n", err.Error()) + return err + } + c.writer.Header().Set("Content-Type", "application/html") return nil } -func (c *Context) Text(status int, object string) error { - // TODO +func (c *Context) Text(text string) error { + c.writer.Header().Set("Content-Type", "text/plain") + c.writer.WriteHeader(200) + c.writer.Write([]byte(text)) return nil } diff --git a/main.go b/main.go index d9ff29c..6b3650e 100644 --- a/main.go +++ b/main.go @@ -19,8 +19,10 @@ func TestHandler(c *framework.Context) error { id := c.QueryInt("id", 0) if id == 1 { c.Json(200, "hello world") - } else { - c.Json(200, "test") + } else if id == 2 { + c.Text("test") + } else if id == 3 { + c.HTML("