github.com/ActiveState/cli@v0.0.0-20240508170324-6801f60cd051/internal/testhelpers/srvstatus/srvstatus.go (about)

     1  package srvstatus
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  	"net/http/httptest"
     7  	"strconv"
     8  	"strings"
     9  	"time"
    10  )
    11  
    12  type SrvStatus struct {
    13  	*httptest.Server
    14  	h *Handle
    15  }
    16  
    17  func New() *SrvStatus {
    18  	h := &Handle{}
    19  
    20  	return &SrvStatus{
    21  		Server: httptest.NewServer(h),
    22  		h:      h,
    23  	}
    24  }
    25  
    26  type Handle struct {
    27  }
    28  
    29  func (h *Handle) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    30  	path := strings.TrimPrefix(r.URL.Path, "/")
    31  	segs := strings.SplitN(path, "/", 2)
    32  	codeSeg := segs[0]
    33  	code, err := strconv.Atoi(codeSeg)
    34  	if err != nil {
    35  		w.WriteHeader(http.StatusBadRequest)
    36  		fmt.Fprintln(w, "first segment malformed: should be valid http status code")
    37  		return
    38  	}
    39  
    40  	sleepParam := r.URL.Query().Get("sleep")
    41  	if sleepParam != "" {
    42  		sleepLen, err := strconv.Atoi(sleepParam)
    43  		if err != nil {
    44  			w.WriteHeader(http.StatusBadRequest)
    45  			fmt.Fprintln(w, "sleep param malformed: should be integer")
    46  			return
    47  		}
    48  
    49  		time.Sleep(time.Millisecond * time.Duration(sleepLen))
    50  	}
    51  
    52  	w.WriteHeader(code)
    53  }