~mendelmaleh/dummy

ref: v0.1.0 dummy/cmd/minimalserver/main.go -rw-r--r-- 1.9 KiB
5635acb8Mendel E Go module 10 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
package main

import (
	"image"
	"image/color"
	"image/draw"
	"image/png"
	"io/ioutil"
	"log"
	"net"
	"net/http"
	"runtime"
	"strings"

	"github.com/golang/freetype"
	"github.com/golang/freetype/truetype"
	"golang.org/x/image/font"
	"golang.org/x/image/math/fixed"
	"golang.org/x/net/netutil"
)

type Options struct {
	// image
	Width, Height int
	Colors        []color.RGBA

	// text
	Text      string
	Font      *truetype.Font
	Size, DPI float64
}

func main() {
	filebytes, err := ioutil.ReadFile("luxisr.ttf")
	if err != nil {
		log.Fatal(err)
	}

	ft, err := freetype.ParseFont(filebytes)
	if err != nil {
		log.Fatal(err)
	}

	opt := Options{
		// image
		Width:  2048,
		Height: 2048,
		Colors: []color.RGBA{
			color.RGBA{0x24, 0x29, 0x33, 0xff},
			color.RGBA{0xec, 0xef, 0xf4, 0xff},
		},

		// text
		Text: "t",
		Font: ft,
		Size: 110,
		DPI:  1152,
	}

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		// image
		im := image.NewRGBA(image.Rectangle{image.Point{}, image.Point{opt.Width, opt.Height}})
		draw.Draw(im, im.Bounds(), image.NewUniform(opt.Colors[0]), image.Point{}, draw.Src)

		// text
		if len(strings.TrimSpace(opt.Text)) > 0 {
			face := truetype.NewFace(opt.Font, &truetype.Options{
				Size:              opt.Size,
				DPI:               opt.DPI,
				Hinting:           font.HintingNone,
				GlyphCacheEntries: 2,
			})

			drawer := &font.Drawer{
				Dst:  im,
				Src:  image.NewUniform(opt.Colors[1]),
				Face: face,
			}

			b, x := font.BoundString(face, opt.Text)
			y := b.Max.Y - b.Min.Y

			drawer.Dot = fixed.Point26_6{
				X: (fixed.I(opt.Width) - x) / 2,
				Y: (fixed.I(opt.Height) + y) / 2,
			}

			drawer.DrawString(opt.Text)
		}

		png.Encode(w, im)
		runtime.GC()
	})

	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		log.Fatal(err)
	}

	listener = netutil.LimitListener(listener, 8)
	log.Panic(http.Serve(listener, nil))
}