github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/pkg/couchdb/status.go (about)

     1  package couchdb
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"net/http"
     7  	"strings"
     8  	"time"
     9  
    10  	"github.com/cozy/cozy-stack/pkg/config/config"
    11  	"github.com/cozy/cozy-stack/pkg/prefixer"
    12  	"github.com/labstack/echo/v4"
    13  )
    14  
    15  // CheckStatus checks that the stack can talk to CouchDB, and returns an error
    16  // if it is not the case.
    17  func CheckStatus(ctx context.Context) (time.Duration, error) {
    18  	couch := config.CouchCluster(prefixer.GlobalCouchCluster)
    19  	u := strings.TrimRight(couch.URL.String(), "/") + "/_up"
    20  	req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
    21  	if err != nil {
    22  		return 0, err
    23  	}
    24  	req.Header.Add(echo.HeaderAccept, echo.MIMEApplicationJSON)
    25  	if auth := couch.Auth; auth != nil {
    26  		if p, ok := auth.Password(); ok {
    27  			req.SetBasicAuth(auth.Username(), p)
    28  		}
    29  	}
    30  	before := time.Now()
    31  	res, err := config.CouchClient().Do(req)
    32  	latency := time.Since(before)
    33  	if err != nil {
    34  		return 0, err
    35  	}
    36  	defer res.Body.Close()
    37  	if res.StatusCode < 200 || res.StatusCode >= 300 {
    38  		return 0, fmt.Errorf("Invalid responde code: %d", res.StatusCode)
    39  	}
    40  	return latency, nil
    41  }