简体   繁体   中英

Is the handler suppose to populate content-type in http response header?

Below handler handles GET request, without populating http Response header:

// ListAll handles GET requests and returns all current products
func (p *ProductHandler) ListAll(rw http.ResponseWriter, r *http.Request) {
    p.l.Println("[DEBUG] get all records")

    prods := data.GetProducts()

    err := data.ToJSON(prods, rw)
    if err != nil {
        // we should never be here but log the error just incase
        p.l.Println("[ERROR] serializing product", err)
    }
}

Below handler handles GET request, populating http Response header:

// ListAll handles GET requests and returns all current products
func (p *ProductHandler) ListAll(rw http.ResponseWriter, r *http.Request) {
    p.l.Println("[DEBUG] get all records")

    rw.Header().Add("Content-Type", "application/json")

    prods := data.GetProducts()

    err := data.ToJSON(prods, rw)
    if err != nil {
        // we should never be here but log the error just incase
        p.l.Println("[ERROR] serializing product", err)
    }
}

Both cases are working fine with simple curl request.

For any http client,

When do we need to populate content-type header, before sending the response, to client?

Always read the documentation first!

The answer to this is clearly covered here (emphasis obviously added):

// If WriteHeader has not yet been called, Write calls
// WriteHeader(http.StatusOK) before writing the data. If the Header
// does not contain a Content-Type line, Write adds a Content-Type set
// to the result of passing the initial 512 bytes of written data to
// DetectContentType. Additionally, if the total size of all written
// data is under a few KB and there are no Flush calls, the
// Content-Length header is added automatically.

To explicitly answer your secondary question:

When do we need to populate content-type header?

Any time you don't want it to be automatically detected. Automatic detection is imprecise, so you generally don't want to rely on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM