-
Notifications
You must be signed in to change notification settings - Fork 35
/
main.go
72 lines (61 loc) · 1.94 KB
/
main.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
package main
import (
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"log"
"lorem/api"
"lorem/image"
"lorem/manager"
"net/http"
"os"
"path"
)
func init() {
flags := pflag.NewFlagSet(path.Base(os.Args[0]), pflag.ContinueOnError)
flags.String("host", "127.0.0.1:8080", "host:port for the HTTP server")
flags.String("dir", "./images", "directory of images")
flags.String("cache", "true", "cache processed files")
flags.String("cdn", "", "cdn domain (works only on cache mode). leave empty to serve the files by app")
flags.String("min-width", "8", "minimum supported width")
flags.String("min-height", "8", "minimum supported height")
flags.String("max-width", "2000", "maximum supported width")
flags.String("max-height", "2000", "maximum supported height")
err := flags.Parse(os.Args[1:])
if err != nil {
log.Panic("failed to parse arguments")
}
err = viper.BindPFlags(flags)
if err != nil {
log.Panic("failed to bind flags")
}
viper.AutomaticEnv()
}
func main() {
m, err := manager.New(viper.GetString("dir"))
if err != nil {
log.Panic(err)
}
log.Printf("%d items loaded", m.Total())
a := api.New(m, &image.Imaging{}, &api.Options{
CacheFiles: viper.GetBool("cache"),
CDN: viper.GetString("cdn"),
MinWidth: viper.GetInt("min-width"),
MaxWidth: viper.GetInt("max-width"),
MinHeight: viper.GetInt("min-height"),
MaxHeight: viper.GetInt("max-height"),
})
r := mux.NewRouter()
r.HandleFunc("/image/{category}", a.SizeHandler).Methods(http.MethodGet)
r.HandleFunc("/image", a.SizeHandler).Methods(http.MethodGet)
r.PathPrefix("/").HandlerFunc(a.NotFound)
log.Printf("listening on %s", viper.GetString("host"))
err = http.ListenAndServe(viper.GetString("host"), handlers.CORS(
handlers.AllowedOrigins([]string{"*"}),
handlers.AllowedHeaders([]string{"Content-Type", "X-Requested-With"}),
)(r))
if err != nil {
log.Panic("HTTP server failed to start")
}
}