-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.go
70 lines (56 loc) · 1.7 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
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/spf13/viper"
)
func statError(w http.ResponseWriter, status int) {
msg := fmt.Sprintf("%d - %s", status, http.StatusText(status))
http.Error(w, msg, status)
}
// APIHandler is the public facing http handler, it will respond only to POST or
// PUT requests that match the template name (ex: /my_template)
func APIHandler(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "template")
var data map[string]interface{}
if r.Method != "POST" && r.Method != "PUT" {
statError(w, http.StatusMethodNotAllowed)
} else if r.Header.Get("Content-type") != "application/json" {
statError(w, http.StatusBadRequest)
} else if tmpl, exists := Templates[name]; !exists {
statError(w, http.StatusNotFound)
} else if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
statError(w, http.StatusBadRequest)
} else {
w.Header().Set("Content-Type", "application/pdf")
srv := NewServerEmulator(data, tmpl)
defer srv.Close()
if err := tmpl.WritePDF(srv.BaseURL(), w); err != nil {
log.Print(err)
statError(w, http.StatusInternalServerError)
}
}
}
// Router builds the http router.
func Router() http.Handler {
r := chi.NewRouter()
r.Use(middleware.StripSlashes)
r.Use(middleware.Logger)
r.Use(middleware.DefaultCompress)
r.HandleFunc("/{template}", APIHandler)
return r
}
func main() {
if err := ConfigRead(); err != nil {
log.Fatal(err)
}
addr := fmt.Sprintf("%s:%d", viper.GetString("addr"), viper.GetInt("port"))
log.Printf("accepting connections on %s", addr)
if err := http.ListenAndServe(addr, Router()); err != nil {
log.Fatal(err)
}
}