github.com/kuoss/venti@v0.2.20/pkg/service/remote/remote.go (about)

     1  package remote
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  	"net/url"
     9  	"time"
    10  
    11  	"github.com/kuoss/common/logger"
    12  	"github.com/kuoss/venti/pkg/model"
    13  )
    14  
    15  type RemoteService struct {
    16  	httpClient *http.Client
    17  	timeout    time.Duration
    18  }
    19  
    20  type Action string
    21  
    22  const (
    23  	ActionHealthy    Action = "/-/healthy"
    24  	ActionReady      Action = "/-/ready"
    25  	ActionMetadata   Action = "/api/v1/metadata"
    26  	ActionQuery      Action = "/api/v1/query"
    27  	ActionQueryRange Action = "/api/v1/query_range"
    28  	ActionTargets    Action = "/api/v1/targets"
    29  )
    30  
    31  func New(httpClient *http.Client, timeout time.Duration) *RemoteService {
    32  	return &RemoteService{
    33  		httpClient: httpClient,
    34  		timeout:    timeout,
    35  	}
    36  }
    37  
    38  func (r *RemoteService) GET(ctx context.Context, datasource *model.Datasource, action Action, rawQuery string) (code int, body string, err error) {
    39  	u, err := url.Parse(datasource.URL)
    40  	if err != nil {
    41  		return 0, "", fmt.Errorf("error on Parse: %w", err)
    42  	}
    43  
    44  	u.Path = string(action)
    45  	u.RawQuery = rawQuery
    46  	ctx, cancel := context.WithTimeout(ctx, r.timeout)
    47  	defer cancel()
    48  	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u.String(), nil)
    49  	if err != nil {
    50  		// unreachable
    51  		return 0, "", fmt.Errorf("NewRequest err: %w", err)
    52  	}
    53  
    54  	if datasource.BasicAuth {
    55  		// TODO: test cover
    56  		req.SetBasicAuth(datasource.BasicAuthUser, datasource.BasicAuthPassword)
    57  	}
    58  	resp, err := r.httpClient.Do(req)
    59  	if err != nil {
    60  		return 0, "", fmt.Errorf("error on Do: %w", err)
    61  	}
    62  	code = resp.StatusCode
    63  	bodyBytes, err := io.ReadAll(resp.Body)
    64  	if err != nil {
    65  		// unreachable
    66  		return code, "", fmt.Errorf("error on ReadAll: %w", err)
    67  	}
    68  	if code != 200 {
    69  		logger.Debugf("code=%d url=%s", code, u.String())
    70  	}
    71  	return code, string(bodyBytes), nil
    72  }