## 內容渲染
Web處理程序可以返回各種內容類型,例如,JSON,純文本,圖像等。 通常在與API通信時,可以指定并接收內容類型,以闡明將傳入數據的格式以及要接收的數據。
本節將通過第三方庫對數據格式進行切換。
### 實踐
1. 獲取第三方庫:
```
go get github.com/unrolled/render
```
2. 建立 negotiate.go:
```
package negotiate
import (
"net/http"
"github.com/unrolled/render"
)
// Negotiator 封裝render并對ContentType進行一些切換
type Negotiator struct {
ContentType string
*render.Render
}
// GetNegotiator 接收http請求 并從Content-Type標頭中找出ContentType
func GetNegotiator(r *http.Request) *Negotiator {
contentType := r.Header.Get("Content-Type")
return &Negotiator{
ContentType: contentType,
Render: render.New(),
}
}
```
3. 建立 respond.go:
```
package negotiate
import "io"
import "github.com/unrolled/render"
// Respond 根據 Content Type 判斷應該返回什么樣類型的數據
func (n *Negotiator) Respond(w io.Writer, status int, v interface{}) {
switch n.ContentType {
case render.ContentJSON:
n.Render.JSON(w, status, v)
case render.ContentXML:
n.Render.XML(w, status, v)
default:
n.Render.JSON(w, status, v)
}
}
```
4. 建立 handler.go:
```
package negotiate
import (
"encoding/xml"
"net/http"
)
// Payload 甚至數據模板
type Payload struct {
XMLName xml.Name `xml:"payload" json:"-"`
Status string `xml:"status" json:"status"`
}
// Handler 調用GetNegotiator處理返回格式
func Handler(w http.ResponseWriter, r *http.Request) {
n := GetNegotiator(r)
n.Respond(w, http.StatusOK, &Payload{Status: "Successful!"})
}
```
5. 建立 main.go:
```
package main
import (
"fmt"
"net/http"
"github.com/agtorre/go-cookbook/chapter7/negotiate"
)
func main() {
http.HandleFunc("/", negotiate.Handler)
fmt.Println("Listening on port :3333")
err := http.ListenAndServe(":3333", nil)
panic(err)
}
```
6. 運行:
```
$ go run main.go
Listening on port :3333
$curl "http://localhost:3333 -H "Content-Type: text/xml"
<payload><status>Successful!</status></payload>
$curl "http://localhost:3333 -H "Content-Type: application/json"
{"status":"Successful!"}
```
### 說明
github.com/unrolled/render 包可以幫助你處理各種類型的請求頭。請求頭通常包含多個值,您的代碼必須考慮到這一點。
* * * *
學識淺薄,錯誤在所難免。歡迎在群中就本書提出修改意見,以饗后來者,長風拜謝。
Golang中國(211938256)
beego實戰(258969317)
Go實踐(386056972)
- 前言
- 第一章 I/O和文件系統
- 常見 I/O 接口
- 使用bytes和strings包
- 操作文件夾和文件
- 使用CSV格式化數據
- 操作臨時文件
- 使用 text/template和HTML/templates包
- 第二章 命令行工具
- 解析命令行flag標識
- 解析命令行參數
- 讀取和設置環境變量
- 操作TOML,YAML和JSON配置文件
- 操做Unix系統下的pipe管道
- 處理信號量
- ANSI命令行著色
- 第三章 數據類型轉換和解析
- 數據類型和接口轉換
- 使用math包和math/big包處理數字類型
- 貨幣轉換和float64注意事項
- 使用指針和SQL Null類型進行編碼和解碼
- 對Go數據編碼和解碼
- Go中的結構體標簽和反射
- 通過閉包實現集合操作
- 第四章 錯誤處理
- 錯誤接口
- 使用第三方errors包
- 使用log包記錄錯誤
- 結構化日志記錄
- 使用context包進行日志記錄
- 使用包級全局變量
- 處理恐慌
- 第五章 數據存儲
- 使用database/sql包操作MySQL
- 執行數據庫事務接口
- SQL的連接池速率限制和超時
- 操作Redis
- 操作MongoDB
- 創建存儲接口以實現數據可移植性
- 第六章 Web客戶端和APIs
- 使用http.Client
- 調用REST API
- 并發操作客戶端請求
- 使用OAuth2
- 實現OAuth2令牌存儲接口
- 封裝http請求客戶端
- 理解GRPC的使用
- 第七章 網絡服務
- 處理Web請求
- 使用閉包進行狀態處理
- 請求參數驗證
- 內容渲染
- 使用中間件
- 構建反向代理
- 將GRPC導出為JSON API
- 第八章 測試
- 使用標準庫進行模擬
- 使用Mockgen包
- 使用表驅動測試
- 使用第三方測試工具
- 模糊測試
- 行為驅動測試
- 第九章 并發和并行
- 第十章 分布式系統
- 第十一章 響應式編程和數據流
- 第十二章 無服務器編程
- 第十三章 性能改進