文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
Using the render package
If you want rendering JSON and HTML to be even simpler, there is the github.com/unrolled/render
package. This package was inspired by the martini-contrib/render
package and is my goto when it comes to rendering data for presentation in my web applications.
package main
import (
"net/http"
"gopkg.in/unrolled/render.v1"
)
func main() {
r := render.New(render.Options{})
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
w.Write([]byte("Welcome, visit sub pages now."))
})
mux.HandleFunc("/data", func(w http.ResponseWriter, req *http.Request) {
r.Data(w, http.StatusOK, []byte("Some binary data here."))
})
mux.HandleFunc("/json", func(w http.ResponseWriter, req *http.Request) {
r.JSON(w, http.StatusOK, map[string]string{"hello": "json"})
})
mux.HandleFunc("/html", func(w http.ResponseWriter, req *http.Request) {
// Assumes you have a template in ./templates called "example.tmpl"
// $ mkdir -p templates && echo "<h1>Hello {{.}}.</h1>" > templates/example.tmpl
r.HTML(w, http.StatusOK, "example", nil)
})
http.ListenAndServe(":8080", mux)
}
Exercises
- Have fun playing with all of the options available when calling
render.New()
- Try using the
.yield
helper function (with the curly braces) and a layout with HTML templates.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论