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("

你好世界

", nil) } return nil } @@ -58,7 +60,7 @@ func main() { server.ListenAndServe() }() - quit := make(chan os.Signal) + quit := make(chan os.Signal, 1) // ctrl+c : SIGINT // ctrl+\ : SIGQUIT @@ -69,7 +71,7 @@ func main() { <-quit fmt.Println("shutdown...") - ticker := time.NewTicker(5 * time.Second) + ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() <-ticker.C