forked from tleyden/open-ocr
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ocr_postback_client.go
78 lines (66 loc) · 2.02 KB
/
ocr_postback_client.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
package ocrworker
import (
"bytes"
"encoding/json"
"io"
"net/http"
"os"
"time"
"github.com/rs/zerolog/log"
"github.com/rs/zerolog"
)
var (
postTimeout = 50 * time.Second
version string
)
type ocrPostClient struct{}
func newOcrPostClient() *ocrPostClient {
return &ocrPostClient{}
}
func (*ocrPostClient) postOcrRequest(ocrResult *OcrResult, replyToAddress string, numTry uint) error {
logger := zerolog.New(os.Stdout).With().Str("RequestID", ocrResult.ID).Timestamp().Logger()
logger.Info().Str("component", "OCR_HTTP").
Uint("attempt", numTry).
Str("replyToAddress", replyToAddress).
Msg("sending ocr back to requester")
jsonReply, err := json.Marshal(ocrResult)
if err != nil {
ocrResult.Status = "error"
}
req, err := http.NewRequest("POST", replyToAddress, bytes.NewBuffer(jsonReply))
if err != nil {
logger.Error().Str("component", "OCR_HTTP").Err(err).Msg("forming POST reply error")
}
req.Close = true
req.Header.Set("User-Agent", "open-ocr/"+version)
req.Header.Set("X-open-ocr-reply-type", "automated reply")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: postTimeout}
resp, err := client.Do(req)
if err != nil {
logger.Warn().Err(err).Str("component", "OCR_HTTP").
Str("replyToAddress", replyToAddress).
Msg("ocr was not delivered. Target did not respond")
return err
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
log.Warn().Err(err).Caller().Str("component", "OCR_HTTP").Msg(req.RequestURI + " response Body could not be removed")
}
}(resp.Body)
body, err := io.ReadAll(resp.Body)
header := resp.StatusCode
if err != nil {
logger.Warn().Err(err).Str("component", "OCR_HTTP").
Str("replyToAddress", replyToAddress).
Msg("ocr was probably not delivered, response body is empty")
return err
}
logger.Info().Str("component", "OCR_HTTP").
Int("RESPONSE_CODE", header).
Str("replyToAddress", replyToAddress).
Interface("payload(first 32 bytes)", string(body[0:32])).
Msg("target responded")
return err
}