-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve.go
91 lines (76 loc) · 1.86 KB
/
serve.go
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
package commands
import (
"github.com/deissh/avagen/plugins"
"github.com/spf13/cobra"
"github.com/valyala/fasthttp"
"log"
"net/http"
"strconv"
"time"
)
var ServerCmd = &cobra.Command{
Use: "serve",
Aliases: []string{"s"},
Short: "Serve avatars",
RunE: AvatarServeCmdF,
}
func init() {
ServerCmd.Flags().String("addr", "0.0.0.0:8080", "TCP address to listen to")
ServerCmd.Flags().Bool("compress", false, "Whether to enable transparent response compression")
RootCmd.AddCommand(ServerCmd)
}
func AvatarServeCmdF(command *cobra.Command, args []string) error {
h := requestHandler
compress, err := command.Flags().GetBool("compress")
if err != nil {
return err
}
if compress {
h = fasthttp.CompressHandler(h)
}
addr, err := command.Flags().GetString("addr")
if err != nil {
return err
}
log.Printf("Server started on %s", addr)
return fasthttp.ListenAndServe(addr, h)
}
func requestHandler(ctx *fasthttp.RequestCtx) {
begin := time.Now()
defer func() {
log.Printf("%v | %s %s - %v - %v",
ctx.RemoteAddr(),
ctx.Method(),
ctx.RequestURI(),
ctx.Response.Header.StatusCode(),
time.Now().Sub(begin),
)
}()
// default values
args := plugins.ParsedArg{
"plugin": "identicon",
}
ctx.QueryArgs().VisitAll(func(key, value []byte) {
args[string(key)] = string(value)
})
plugin, err := plugins.Get(args["plugin"])
if err != nil {
ctx.SetStatusCode(http.StatusNotFound)
return
}
args, err = plugins.ValidateArgs(plugin, args)
if err != nil {
ctx.SetStatusCode(http.StatusBadRequest)
ctx.WriteString(err.Error())
return
}
data, err := plugin.Generate(args)
if err != nil {
log.Fatalln(err)
return
}
ctx.Response.Header.Set("Content-Type", "image/"+args["type"])
ctx.Response.Header.Set("Cache-Control", "max-age=600")
ctx.Response.Header.Set("Content-Length", strconv.Itoa(len(data)))
ctx.SetBody(data)
}