github.com/PDOK/gokoala@v0.50.6/internal/engine/problems.go (about)

     1  package engine
     2  
     3  import (
     4  	"log"
     5  	"net/http"
     6  	"time"
     7  
     8  	"schneider.vip/problem"
     9  )
    10  
    11  const (
    12  	timestampKey             = "timestamp"
    13  	defaultMessageServerErr  = "An unexpected error has occurred, try again or contact support if the problem persists"
    14  	defaultMessageBadGateway = "Failed to proxy request, try again or contact support if the problem persists"
    15  )
    16  
    17  type ProblemKind int
    18  
    19  var Now = time.Now // allow mocking
    20  
    21  // The following problems should be added to openapi/problems.go.json
    22  var (
    23  	ProblemBadRequest    = ProblemKind(http.StatusBadRequest)
    24  	ProblemNotFound      = ProblemKind(http.StatusNotFound)
    25  	ProblemNotAcceptable = ProblemKind(http.StatusNotAcceptable)
    26  	ProblemServerError   = ProblemKind(http.StatusInternalServerError)
    27  	ProblemBadGateway    = ProblemKind(http.StatusBadGateway)
    28  )
    29  
    30  // RenderProblem writes RFC 7807 (https://tools.ietf.org/html/rfc7807) problem to client.
    31  // Only the listed problem kinds are supported since they should be advertised in the OpenAPI spec.
    32  // Optionally a caller may add a details (single string) about the problem. Warning: Be sure to not
    33  // include sensitive information in the details string!
    34  func RenderProblem(kind ProblemKind, w http.ResponseWriter, details ...string) {
    35  	p := problem.Of(int(kind))
    36  	if kind == ProblemServerError { //nolint:gocritic // switch not handy here
    37  		p = p.Append(problem.Detail(defaultMessageServerErr))
    38  	} else if kind == ProblemBadGateway {
    39  		p = p.Append(problem.Detail(defaultMessageBadGateway))
    40  	} else if len(details) > 0 {
    41  		p = p.Append(problem.Detail(details[0]))
    42  	}
    43  	p = p.Append(problem.Custom(timestampKey, Now().UTC().Format(time.RFC3339)))
    44  	_, err := p.WriteTo(w)
    45  	if err != nil {
    46  		log.Printf("failed to write response: %v", err)
    47  	}
    48  }