Skip to content

Instantly share code, notes, and snippets.

@malisetti
Last active September 10, 2019 08:40
Show Gist options
  • Save malisetti/4df5ab905bdcd1fcc9a5138658370913 to your computer and use it in GitHub Desktop.
Save malisetti/4df5ab905bdcd1fcc9a5138658370913 to your computer and use it in GitHub Desktop.
A simple web server to convert GIF from an url to compressed archive of images
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"fmt"
"image/gif"
"image/png"
"io"
"log"
"net/http"
)
const (
BYTE = 1 << (10 * iota) // 1 byte
KILOBYTE
MEGABYTE
GIGABYTE
TERABYTE
PETABYTE
EXABYTE
)
func gifToTar(name string, r io.Reader) (io.Reader, error) {
g, err := gif.DecodeAll(r)
if err != nil {
return nil, err
}
var out bytes.Buffer
tw := tar.NewWriter(&out)
for i, pi := range g.Image {
var buf bytes.Buffer
err = png.Encode(&buf, pi)
if err != nil {
return nil, err
}
byts := buf.Bytes()
err = tw.WriteHeader(&tar.Header{
Name: fmt.Sprintf("%s_%d.%s", name, i, "png"),
Size: int64(len(byts)),
Mode: 0600,
})
if err != nil {
return nil, err
}
_, err = tw.Write(byts)
if err != nil {
return nil, err
}
}
if err := tw.Flush(); err != nil {
return nil, err
}
if err := tw.Close(); err != nil {
return nil, err
}
return &out, nil
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
gurl := r.URL.Query().Get("gif")
resp, err := http.Get(gurl)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "err: %s", err.Error())
return
}
defer resp.Body.Close()
ctypes := resp.Header["Content-Type"]
switch ctypes[0] {
// case "image/webp":
// img, err = webp.Decode(resp.Body)
case "image/gif":
default:
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "err: unsupported format %s : supports image/gif alone.", ctypes[0])
return
}
}
lr := io.LimitReader(resp.Body, 100*KILOBYTE)
br, err := gifToTar("thumb", lr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
fmt.Fprintf(w, "err: %s", err.Error())
return
}
w.Header().Set("Content-Disposition", "attachment; filename=images.tar.gz")
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Content-Type", "application/tar+gzip")
w.WriteHeader(http.StatusOK)
gzw := gzip.NewWriter(w)
io.Copy(gzw, br)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment