-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
106 lines (83 loc) · 2.46 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
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
package main
import (
"bytes"
"embed"
"encoding/json"
"errors"
"flag"
"fmt"
"io/fs"
"net/http"
"os/exec"
"github.com/ams-pro/management-api/auth"
"github.com/hashicorp/go-hclog"
"github.com/aaronschweig/auto-sdb/extractor"
)
type ErrResponse struct {
Message string `json:"message"`
}
var (
//go:embed frontend/build/* frontend/build/_app/pages/* frontend/build/_app/assets/pages/*
frontend embed.FS
)
func writeError(rw http.ResponseWriter, statusCode int, err error) {
rw.WriteHeader(statusCode)
rw.Header().Add("Content-Type", "application/json")
json.NewEncoder(rw).Encode(&ErrResponse{err.Error()})
}
func extractSDB(log hclog.Logger) func(http.ResponseWriter, *http.Request) {
return func(rw http.ResponseWriter, r *http.Request) {
file, _, err := r.FormFile("file")
if err != nil {
log.Error("error reading file", "error", err)
writeError(rw, http.StatusBadRequest, err)
return
}
defer file.Close()
cmd := exec.Command("gs", "-sDEVICE=txtwrite", "-dBATCH", "-dNOPAUSE", "-sOutputFile=-", "-")
cmd.Stdin = file
var buffer bytes.Buffer
cmd.Stdout = &buffer
err = cmd.Run()
if err != nil {
log.Error("could not process pdf with gs", "error", err)
writeError(rw, http.StatusInternalServerError, err)
return
}
result := extractor.Extract(buffer.String(), log)
rw.Header().Add("Content-Type", "application/json")
json.NewEncoder(rw).Encode(&result)
}
}
func post(f http.HandlerFunc) http.HandlerFunc {
return func(rw http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.NotFound(rw, r)
return
}
if auth.IsAuthenticated(r.Context()) {
f.ServeHTTP(rw, r)
} else {
writeError(rw, http.StatusUnauthorized, errors.New("please provide a valid access_token"))
}
}
}
func main() {
port := flag.String("port", "3000", "the port for the application to run on")
dev := flag.Bool("dev", false, "start server in dev mode and do not bundle frontend in binary")
flag.Parse()
log := hclog.Default()
mux := http.NewServeMux()
if *dev {
mux.Handle("/", http.FileServer(http.Dir("./frontend/build")))
} else {
static, err := fs.Sub(frontend, "frontend/build")
if err != nil {
panic(err)
}
mux.Handle("/", http.FileServer(http.FS(static)))
}
mux.Handle("/extract", auth.Middleware(post(extractSDB(log)), "evaluate-ams-pro.eu.auth0.com"))
log.Info(fmt.Sprintf("Application is up and running on http://localhost:%s", *port))
http.ListenAndServe(fmt.Sprintf(":%s", *port), mux)
}