go - serving up pdfs using golang -
just wondering if guys can code.
it works serving images not pdf brochure. in advance
func main(){ http.handlefunc("/", func(w http.responsewriter, r *http.request){ filename := "/var/www/filedipenser/brochure.pdf" streampdfbytes, err := ioutil.readfile( filename ) if err != nil { fmt.println(err) os.exit(1) } b := bytes.newbuffer(streampdfbytes) w.header().set("content-type", "application/pdf") if _, err := b.writeto(w); err != nil { fmt.fprintf(w, "%s", err) } w.write([]byte("pdf generated")) }) err := http.listenandserve(":4111", nil) if err != nil { log.fatal("listenandserve: ", err) fmt.println(err) } }
the code bit inefficient appears working. however, pdf viewers might sensitive extraneous output adding end of http response stream. remove w.write([]byte("pdf generated"))
corrupting output. change fmt.println
if wanted debugging purposes.
the inefficiency because loading entire pdf file memory send client. large files waste memory. better open file , stream directly file (an io.reader) response (an io.writer) using io.copy. like:
// open file f, err := os.open(filename) if err != nil { fmt.println(err) w.writeheader(500) return } defer f.close() //set header w.header().set("content-type", "application/pdf") //stream response if _, err := io.copy(w, f); err != nil { fmt.println(err) w.writeheader(500) }
you want handle errors better, example. however, important client provided http error response when encounter error aware request failed.
Comments
Post a Comment