Skip to content

Instantly share code, notes, and snippets.

@ocpodariu
Created May 16, 2019 12:09
Show Gist options
  • Save ocpodariu/b03bb76873dcce1cd997e88f6e654088 to your computer and use it in GitHub Desktop.
Save ocpodariu/b03bb76873dcce1cd997e88f6e654088 to your computer and use it in GitHub Desktop.
Serve external images from Go
package main
import (
"bytes"
"io/ioutil"
"log"
"net/http"
"time"
)
func main() {
http.HandleFunc("/stream", serveImg)
log.Fatal(http.ListenAndServe(":9531", nil))
}
func serveImg(w http.ResponseWriter, req *http.Request) {
imgURL := "https://static.independent.co.uk/s3fs-public/thumbnails/imaASDge/2017/09/12/11/naturo-monkey-selfie.jpg?w968"
resp, err := http.Get(imgURL)
if err != nil {
log.Printf("GET: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
defer resp.Body.Close()
buf, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Printf("read image: %v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
http.ServeContent(w, req, "", time.Time{}, bytes.NewReader(buf))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment