~mendelmaleh/dummy

ref: b862a107cb4810e7514eccf69deb3fc5f6f5dc4c dummy/cmd/dummyserver/archive.go -rw-r--r-- 2.1 KiB
b862a107Mendel E Document new endpoints 1 year, 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main

import (
	"archive/tar"
	"archive/zip"
	"bytes"
	"fmt"
	"image/png"
	"io"
	"net/http"

	"git.sr.ht/~mendelmaleh/dummy"
)

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 {
		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.zip\"")
	w.Header().Set("Content-Type", "application/zip")

	archive := zip.NewWriter(w)

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

		file, err := archive.Create(f.name + ".png")
		if err != nil {
			fmt.Fprintln(w, err)
			return
		}

		png.Encode(file, dummy.Image(opt.Options))
	}

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

}