Skip to content

Instantly share code, notes, and snippets.

@jonfriesen
Created August 19, 2021 20:44
Show Gist options
  • Save jonfriesen/298179dcdd26178e6f7d360560d3b6d0 to your computer and use it in GitHub Desktop.
Save jonfriesen/298179dcdd26178e6f7d360560d3b6d0 to your computer and use it in GitHub Desktop.
Example function to proxy a PDF from one URL to a http handler func
package main
import (
"fmt"
"io"
"net"
"net/http"
"time"
)
func main() {
pdfLocation := "http://www.bcregistryservices.gov.bc.ca/local/bcreg/documents/forms/reg50a.pdf"
fileName := fmt.Sprintf("%s_%s-%d.pdf", "Alice", "Smith", time.Now().Unix())
http.HandleFunc("/", getFileProxyHandler(pdfLocation, fileName))
fmt.Println("Listening on port 8080")
err := http.ListenAndServe(":8080", nil)
if err != nil {
// TODO(jon) handle error
panic(err)
}
}
func getFileProxyHandler(url, fileName string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// this might have to change depending on api2pdf delays
timeout := time.Duration(30) * time.Second
transport := &http.Transport{
ResponseHeaderTimeout: timeout,
Dial: func(network, addr string) (net.Conn, error) {
return net.DialTimeout(network, addr, timeout)
},
DisableKeepAlives: true,
}
client := &http.Client{
Transport: transport,
}
resp, err := client.Get(url)
if err != nil {
// TODO(jon) handle error
panic(err)
}
defer resp.Body.Close()
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName))
w.Header().Set("Content-Type", resp.Header.Get("Content-Type"))
w.Header().Set("Content-Length", resp.Header.Get("Content-Length"))
_, err = io.Copy(w, resp.Body)
if err != nil && err != io.EOF {
// TODO(jon) handle error
panic(err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment