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

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法