-
Notifications
You must be signed in to change notification settings - Fork 0
/
micro.go
64 lines (58 loc) · 1.61 KB
/
micro.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
package main
import (
"bytes"
"io"
"net/http"
"github.com/goccy/go-json"
"github.com/nats-io/nats.go"
"github.com/nats-io/nats.go/micro"
)
func RegisterNatsService(nc *nats.Conn) {
extractService, err := micro.AddService(nc, micro.Config{
Name: "extract-text",
Version: "1.0.0",
Description: "Returns the plain text content of binary files like PDFs",
})
if err != nil {
panic(err)
}
extractService.AddEndpoint("extract-remote",
micro.HandlerFunc(HandleUrl),
micro.WithEndpointQueueGroup("text-extraction-service"))
extractService.AddEndpoint("update-cache",
micro.HandlerFunc(UpdateCache),
micro.WithEndpointQueueGroup("text-extraction-service"))
}
// HandleUrl replies to a Nats request
func HandleUrl(req micro.Request) {
d := req.Data()
var params RequestParams
err := json.Unmarshal(d, ¶ms)
if err != nil {
req.Error("invalid_params", err.Error(), nil)
return
}
logger.Info("Received Nats request", "params", params)
var b bytes.Buffer
header := http.Header{}
_, err = DocFromUrl(params, &b, header)
if err != nil {
req.Error("failed", err.Error(), nil)
return
}
req.Respond(b.Bytes(), micro.WithHeaders(micro.Headers(header)))
}
// UpdateCache responds with 'done' once a document has been added
// or refreshed in the cache
func UpdateCache(req micro.Request) {
url := string(req.Data())
params := RequestParams{Url: url, Silent: true}
logger.Info("Received Nats request", "params", params)
header := http.Header{}
_, err := DocFromUrl(params, io.Discard, header)
if err != nil {
req.Error("failed", err.Error(), nil)
return
}
req.Respond([]byte("done"))
}