Skip to content

Commit

Permalink
String function for Status
Browse files Browse the repository at this point in the history
Viewing the status code as a string is a bit awkward if we use int. The change adds the String function so that it's more human readable.
  • Loading branch information
VoyTechnology committed Oct 2, 2023
1 parent 3c26b0d commit e650a22
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
14 changes: 14 additions & 0 deletions grpchealth.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,20 @@ const (
StatusNotServing Status = 2
)

// String representation of the status.
func (s Status) String() string {
switch s {
case StatusUnknown:
return "unknown"
case StatusServing:
return "serving"
case StatusNotServing:
return "not_serving"
}

return fmt.Sprintf("status_%d", s)
}

// NewHandler wraps the supplied Checker to build an HTTP handler for gRPC's
// health-checking API. It returns the path on which to mount the handler and
// the HTTP handler itself.
Expand Down
20 changes: 20 additions & 0 deletions grpchealth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,32 @@ import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"

"connectrpc.com/connect"
healthv1 "connectrpc.com/grpchealth/internal/gen/go/connectext/grpc/health/v1"
)

func TestCode(t *testing.T) {
t.Parallel()
// Since we only have 3 codes we can hardcode them
valid := map[Status]bool{
StatusUnknown: true,
StatusServing: true,
StatusNotServing: true,
Status(128): false,
}

// Ensures we don't forget to update the [fmt.Stringer] methods.
for status, wantValid := range valid {
got := status.String()
if gotValid := !strings.HasPrefix(got, "status_"); wantValid != gotValid {
t.Errorf("status.String() = %v, valid = %v, want valid = %v", got, gotValid, wantValid)
}
}
}

func TestHealth(t *testing.T) {
const (
userFQN = "acme.user.v1.UserService"
Expand Down

0 comments on commit e650a22

Please sign in to comment.