Created
May 16, 2019 12:09
-
-
Save ocpodariu/b03bb76873dcce1cd997e88f6e654088 to your computer and use it in GitHub Desktop.
Serve external images from Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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