~mendelmaleh/dummy

d0dd20f1379d448e3306fac63d9f7d6030386b48 — Mendel E 1 year, 30 days ago e97e60a
Add tar endpoint
1 files changed, 68 insertions(+), 0 deletions(-)

M cmd/dummyserver/main.go
M cmd/dummyserver/main.go => cmd/dummyserver/main.go +68 -0
@@ 1,10 1,13 @@
package main

import (
	"archive/tar"
	"archive/zip"
	"bytes"
	"fmt"
	"html/template"
	"image/png"
	"io"
	"io/ioutil"
	"log"
	"net"


@@ 98,6 101,12 @@ func main() {
		},
	)

	http.HandleFunc(config.Dummy.Pattern+"tar/",
		func(w http.ResponseWriter, r *http.Request) {
			Tar(w, r, Options{dopt.Copy()})
		},
	)

	http.HandleFunc(config.Dummy.Pattern+"zip/",
		func(w http.ResponseWriter, r *http.Request) {
			Zip(w, r, Options{dopt.Copy()})


@@ 138,6 147,65 @@ func Dummy(w http.ResponseWriter, r *http.Request, opt Options) {
	// fmt.Fprintf(w, "%+v\n", dopt)
}

func Tar(w http.ResponseWriter, r *http.Request, opt Options) {
	err := r.ParseForm()
	if err != nil {
		fmt.Fprintln(w, err)
		return
	}

	err = opt.FromForm(r.Form)
	if err != nil {
		fmt.Fprintln(w, err)
		return
	}

	files := []struct {
		name string
		size int
	}{
		{"favicon-16x16", 16},
		{"favicon-32x32", 32},
		{"apple-touch-icon", 180},
		{"android-chrome-192x192", 192},
		{"android-chrome-512x512", 512},
	}

	w.Header().Set("Content-Disposition", "attachment; filename=\"favicons.tar\"")
	w.Header().Set("Content-Type", "application/tar")

	archive := tar.NewWriter(w)

	for _, f := range files {
		opt.Width, opt.Height = f.size, f.size
		opt.DPI = float64(f.size) / 128 * 72

		var buf bytes.Buffer
		png.Encode(&buf, dummy.Image(opt.Options))

		hdr := &tar.Header{
			Name: f.name,
			Mode: 0600,
			Size: int64(buf.Len()),
		}

		if err := archive.WriteHeader(hdr); err != nil {
			fmt.Fprintln(w, err)
			return
		}

		if _, err := io.Copy(archive, &buf); err != nil {
			fmt.Fprintln(w, err)
			return
		}
	}

	if err := archive.Close(); err != nil {
		fmt.Fprintln(w, err)
		return
	}
}

func Zip(w http.ResponseWriter, r *http.Request, opt Options) {
	err := r.ParseForm()
	if err != nil {