aboutsummaryrefslogtreecommitdiff
path: root/api/external_services.go
blob: c467171d275002768f9fc03dbdf26880eeed9bd4 (plain) (blame)
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
package api

import (
	"context"
	"fmt"
	"time"
)

// Use this to call external services. It will handle timeout and request cancellation gracefully.
func CallExternalService(tag string, timeout time.Duration, routine func() *Error) *Error {
	routineDone := make(chan *Error)

	go func() {
		routineDone <- routine()
	}()

	ctx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	select {
	case err := <-routineDone:
		return err
	case <-ctx.Done():
		return &Error{ExternalServiceTimeout, "external service timeout", fmt.Errorf("'%v' routine timeouted", tag)}
	}
}

var ErrorChan chan error

func ErrorMonitoring() {
	for {
		err := <-ErrorChan
		log.Errorf("error: %v", err)
	}
}

func init() {
	ErrorChan = make(chan error)
	go ErrorMonitoring()
}