如何在Golang中将JSON响应函数转换为HTML/文本输出
要让你的Go API支持HTML和文本响应,你可以在现有JSON响应的基础上扩展对应的输出函数,同时支持根据请求自动选择格式,具体实现如下:
扩展多格式响应支持
1. 添加文本和HTML响应的基础函数
先新增两个和writeJSONResponse同级的响应输出函数:
文本响应函数
func writeTextResponse(w http.ResponseWriter, statusCode int, message string) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(statusCode) w.Write([]byte(message)) }
HTML响应函数
如果是简单场景可以直接拼接HTML,复杂场景建议用Go模板引擎,这里先写基础实现:
import "fmt" func writeHTMLResponse(w http.ResponseWriter, statusCode int, title, content string) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.WriteHeader(statusCode) htmlContent := fmt.Sprintf(` <!DOCTYPE html> <html> <head> <title>%s</title> <meta charset="utf-8"> </head> <body> <h1>%s</h1> <div>%s</div> </body> </html>`, title, title, content) w.Write([]byte(htmlContent)) }
2. 修改错误响应,适配多格式输出
把原来的writeErrorResponse改成支持指定格式的版本:
func writeErrorResponse(w http.ResponseWriter, r *http.Request, statusCode int, message string, format string) { switch format { case "json": response := map[string]interface{}{ "error": message, "links": []map[string]string{ { "rel": "self", "href": r.URL.Path, }, }, } writeJSONResponse(w, statusCode, response) case "text": textMsg := fmt.Sprintf("Error %d: %s\nSelf link: %s", statusCode, message, r.URL.Path) writeTextResponse(w, statusCode, textMsg) case "html": title := fmt.Sprintf("Error %d", statusCode) content := fmt.Sprintf("<p>%s</p><p>Self link: <a href=\"%s\">%s</a></p>", message, r.URL.Path, r.URL.Path) writeHTMLResponse(w, statusCode, title, content) default: // 默认 fallback 到JSON格式 writeErrorResponse(w, r, statusCode, message, "json") } }
3. 自动识别客户端期望的响应格式
添加一个函数,通过请求的Accept头或者URL查询参数来判断要返回的格式:
import "strings" func getResponseFormat(r *http.Request) string { // 优先取URL参数里的format值,比如 ?format=html formatParam := r.URL.Query().Get("format") if formatParam != "" { switch strings.ToLower(formatParam) { case "html", "text", "json": return formatParam } } // 解析Accept头判断客户端偏好 acceptHeader := r.Header.Get("Accept") switch { case strings.Contains(acceptHeader, "text/html"): return "html" case strings.Contains(acceptHeader, "text/plain"): return "text" case strings.Contains(acceptHeader, "application/json"): return "json" default: return "json" } }
4. 在Handler中使用多格式响应
比如在你的业务Handler里:
func exampleHandler(w http.ResponseWriter, r *http.Request) { // 模拟错误场景 errMsg := "请求的资源不存在" format := getResponseFormat(r) writeErrorResponse(w, r, http.StatusNotFound, errMsg, format) }
5. (可选)扩展成功响应的多格式支持
类似错误响应,你也可以为成功数据添加多格式输出:
func writeSuccessResponse(w http.ResponseWriter, r *http.Request, statusCode int, data interface{}, format string) { switch format { case "json": writeJSONResponse(w, statusCode, data) case "text": // 简单类型直接转字符串,复杂数据需要自定义转换逻辑 text, ok := data.(string) if !ok { text = fmt.Sprintf("%v", data) } writeTextResponse(w, statusCode, text) case "html": title := "请求成功" content := fmt.Sprintf("<p>返回数据:%v</p>", data) writeHTMLResponse(w, statusCode, title, content) default: writeJSONResponse(w, statusCode, data) } }
内容的提问来源于stack exchange,提问作者Livera Team
相关产品推荐
相关产品推荐

