適当な画像URLから、その画像をブラウザでダウンロードさせるサンプルです。
ぼくは最初、画像URLから取得した画像を "適当なファイルとして保存して圧縮" という流れでやっていましたが。この "保存して" という処理を省きたかったのです。省いたサンプルが以下になります。
(もっといい方法とかあるのかなぁ..
server.go
package main
import (
"archive/zip"
"io/ioutil"
"net/http"
"html/template"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("index.html")
t.Execute(w, nil)
}
func downloadHandler(w http.ResponseWriter, r *http.Request) {
imageURL := "適当な画像URL"
res, _ := http.Get(imageURL)
data, _ := ioutil.ReadAll(res.Body)
defer res.Body.Close()
zw := zip.NewWriter(w)
defer zw.Close()
writer, _ := zw.Create("create.png")
w.Header().Set("Content-Disposition", "attachment; filename=tmp.zip")
w.Header().Set("Content-Type", "application/zip")
writer.Write(data)
}
func main() {
http.HandleFunc("/", indexHandler)
http.HandleFunc("/download", downloadHandler)
http.ListenAndServe(":8000", nil)
}
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
tmp
<form method="post" action="/download">
<input type="submit" value="Download Image">
</form>
</body>
</html>