Golang HTTP服务器根据请求的内容类型返回 HTML 或 JSON
时间:2024-03-06
浏览:127
作者:佚名
学习Golang要努力,但是不要急!今天的这篇文章《Golang HTTP服务器根据请求的内容类型返回 HTML 或 JSON》将会介绍到等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!
问题内容
我正在尝试使用 gorilla mux 在 golang 中编写简单的 restful 应用程序。 我编写了一些如下所示的处理程序:
func getuser(w http.responsewriter, r *http.request) {
if r.header.get("content-type") == "application/json" {
w.header().set("content-type", "application/json")
u, err := _getuser(r)
if err != nil {
http.notfound(w, r)
return
}
json.newencoder(w).encode(u) //asked for json, return json
} else {
w.header().set("content-type", "text/html")
u, err := _getuser(r)
if err != nil {
http.notfound(w, r)
return
}
rendertemplate(w, "view", u) // asked for html, return html
}
}
func _getuser(r *http.request) (*user, error) {
params := mux.vars(r)
for _, u := range users {
if u.id == params["id"] {
return &u, nil
}
}
return nil, errors.new("")
}
func main() {
router := mux.newrouter()
router.handlefunc("/v1/users/{id}", getuser).methods("get")
}
我遇到的问题是有很多重复。每个 crud 方法都必须检查内容类型并返回 json 或 html。
我想过写一个闭包
func htmlOrJSON(fn func(http.ResponseWriter, *http.Request) (interface {}, error), templateName string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-type") == "application/json" {
w.Header().Set("Content-Type", "application/json")
result, err := fn(w, r)
if err != nil {
http.NotFound(w, r)
return
}
json.NewEncoder(w).Encode(result)
} else {
w.Header().Set("Content-Type", "text/html")
result, err := fn(w, r)
if err != nil {
http.NotFound(w, r)
return
}
renderTemplate(w, templateName, result)
}
}
}
// and use as:
router.HandleFunc("/v1/users/{id}", htmlOrJSON(getUser, "view")).Methods("GET")
要删除重复项,但看起来也不太好。谁能帮我使这段代码更简洁吗?
解决方案
虽然这是一个代码审查问题,应该在 codereview 社区中,但我会尝试回答它。
编写一个处理 html 和 json 渲染的通用函数。即使您重复某些代码,错误处理 imo 也应该在每个处理程序上发生。它在那里更有意义,并使代码更具可读性和明确性。您很快就会发现还有其他错误需要特殊处理。
逻辑上,大多数api接受查询参数http://api.com/user/1?fomtat=json。这更有意义,因为当客户端接受多种内容类型时,您就会陷入困境。
const JSON = "application/json"
func getUser(w http.ResponseWriter, r *http.Request) {
u, err := _getUser(r)
if err != nil {
http.NotFound(w, r)
return
}
responseBody(u, r.Header.Get("Content-type"), &w)
}
func responseBody(u User, contentType string, w io.writer) {
switch contentType {
case JSON:
w.Header().Set("Content-Type", JSON)
json.NewEncoder(w).Encode(u) //asked for json, return json
default:
w.Header().Set("Content-Type", "text/html")
renderTemplate(w, "view", u) // asked for html, return html
}
}以上就是《Golang HTTP服务器根据请求的内容类型返回 HTML 或 JSON》的详细内容,更多关于的资料请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
