restful-html-template.go 728 B

1234567891011121314151617181920212223242526272829303132333435
  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "text/template"
  6. "github.com/emicklei/go-restful"
  7. )
  8. // This example shows how to serve a HTML page using the standard Go template engine.
  9. //
  10. // GET http://localhost:8080/
  11. func main() {
  12. ws := new(restful.WebService)
  13. ws.Route(ws.GET("/").To(home))
  14. restful.Add(ws)
  15. print("open browser on http://localhost:8080/\n")
  16. http.ListenAndServe(":8080", nil)
  17. }
  18. type Message struct {
  19. Text string
  20. }
  21. func home(req *restful.Request, resp *restful.Response) {
  22. p := &Message{"restful-html-template demo"}
  23. // you might want to cache compiled templates
  24. t, err := template.ParseFiles("home.html")
  25. if err != nil {
  26. log.Fatalf("Template gave: %s", err)
  27. }
  28. t.Execute(resp.ResponseWriter, p)
  29. }