aboutsummaryrefslogtreecommitdiff
path: root/api/external_services.go
blob: 41f4d872381cfe9fd3dab1eb58992508f9ead21e (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()
}