aboutsummaryrefslogblamecommitdiff
path: root/api/external_services.go
blob: 41f4d872381cfe9fd3dab1eb58992508f9ead21e (plain) (tree)
1
2
3
4
5
6
7
8
9








                                                                                                  

                                                                                         




























                                                                                                                            
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()
}