forked from meateam/ocr-func
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
91 lines (74 loc) · 1.88 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
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"time"
"handler/function"
// "github.com/alexellis/golang-http-template/template/golang-http/function"
handler "github.com/openfaas-incubator/go-function-sdk"
)
func makeRequestHandler() func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
var input []byte
if r.Body != nil {
defer r.Body.Close()
bodyBytes, bodyErr := ioutil.ReadAll(r.Body)
if bodyErr != nil {
log.Printf("Error reading body from request.")
}
input = bodyBytes
}
req := handler.Request{
Body: input,
Header: r.Header,
Method: r.Method,
QueryString: r.URL.RawQuery,
}
result, resultErr := function.Handle(req)
if result.Header != nil {
for k, v := range result.Header {
w.Header()[k] = v
}
}
if resultErr != nil {
log.Print(resultErr)
w.WriteHeader(http.StatusInternalServerError)
} else {
if result.StatusCode == 0 {
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(result.StatusCode)
}
}
w.Write(result.Body)
}
}
func parseIntOrDurationValue(val string, fallback time.Duration) time.Duration {
if len(val) > 0 {
parsedVal, parseErr := strconv.Atoi(val)
if parseErr == nil && parsedVal >= 0 {
return time.Duration(parsedVal) * time.Second
}
}
duration, durationErr := time.ParseDuration(val)
if durationErr != nil {
return fallback
}
return duration
}
func main() {
readTimeout := parseIntOrDurationValue(os.Getenv("read_timeout"), 10*time.Second)
writeTimeout := parseIntOrDurationValue(os.Getenv("write_timeout"), 10*time.Second)
s := &http.Server{
Addr: fmt.Sprintf(":%d", 8082),
ReadTimeout: readTimeout,
WriteTimeout: writeTimeout,
MaxHeaderBytes: 1 << 20, // Max header of 1MB
}
http.HandleFunc("/", makeRequestHandler())
log.Fatal(s.ListenAndServe())
}