dongyan5706 2019-06-23 09:30
浏览 354
已采纳

Golang HTTP服务器根据内容类型返回html或json

I am trying to write simple RESTful app in Golang using gorilla mux. I wrote few handlers that look as follows:

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")
}

The problem I got here is that I have got a lot of duplication. Every CRUD method would have to check for content type and return either json or html.

I thought about writing a closure

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")

To remove duplication but it also does not look well. Could anyone help me make this code cleaner?

  • 写回答

1条回答 默认 最新

  • dsiftnc99059 2019-06-23 10:07
    关注

    Although this is a code review question and should be in the CodeReview community, I’ll try to answer it.

    Write a generic function that handles HTML and JSON rendering. The error handling IMO should happen on each handler even if you duplicate some code. It makes more sense there and makes the code more readable and explicit. You will soon see that there will be other errors that require special handling.

    On the logic, most APIs accept query parameters http://api.com/user/1?fomtat=json. This makes more sense because when a client accept more than content types you will be stuck.

    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
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题