返回介绍

Using the render package

发布于 2025-02-25 22:26:26 字数 1495 浏览 0 评论 0 收藏 0

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

  1. Have fun playing with all of the options available when calling render.New()
  2. Try using the .yield helper function (with the curly braces) and a layout with HTML templates.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文