chrome and safari don't render images in html template served by a go server with Content-Length is set

76 views Asked by At

I stored some images on GridFS and served the resource with a simple Go web server.

func GetFile(w http.ResponseWriter, r *http.Request) {
    fileObjectId := r.URL.Path[len("/file/"):]
    gfs := db.GridFS("fs")
    file, err := gfs.OpenId(bson.ObjectIdHex(fileObjectId))
    if err != nil {
        panic("file not found")
    }
    w.Header().Set("Content-Length", strconv.FormatInt(file.Size(), 10))
    w.Header().Set("Content-Type", file.ContentType())

    buff := make([]byte, 8192)
    nread, _ := file.Read(buff)
    for nread > 0 {
        w.Write(buff)
        nread, _ = file.Read(buff)
    }
}

The problems:

a. Images don't render in Chrome and Safari if they are placed in img tag in a html template. But firefox does display images pretty well.

b. If access images directly in Chrome and Safari, everything works fine.

c. By removing Content-Length, Chrome and Safari can load images in a html template.

d. I code the same handler with python and pymongo, set both Content-Length and Content-Type, it works in Chrome and Safari.

1

There are 1 answers

1
Jiang YD On

the line w.Write(buff) always to write 8192 bytes, which cause the total length of you HTTP body not equals to the file size.