github.com/aporeto-inc/trireme-lib@v10.358.0+incompatible/controller/internal/enforcer/applicationproxy/http/error_handler.go (about)

     1  package httpproxy
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"net"
     7  	"net/http"
     8  )
     9  
    10  const (
    11  	// TriremeBadGatewayText is the message to send when downstream fails.
    12  	TriremeBadGatewayText = ":The downstream port cannot be accessed. Please validate your service ports and address/hosts configuration"
    13  
    14  	// TriremeGatewayTimeout is the message to send when downstream times-out.
    15  	TriremeGatewayTimeout = ":The downstream node timed-out."
    16  
    17  	// StatusClientClosedRequest non-standard HTTP status code for client disconnection
    18  	StatusClientClosedRequest = 499
    19  
    20  	// StatusClientClosedRequestText non-standard HTTP status for client disconnection
    21  	StatusClientClosedRequestText = "Client Closed Request"
    22  )
    23  
    24  // TriremeHTTPErrHandler Standard error handler
    25  type TriremeHTTPErrHandler struct{}
    26  
    27  func (e TriremeHTTPErrHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, err error) {
    28  	statusCode := http.StatusInternalServerError
    29  
    30  	if e, ok := err.(net.Error); ok {
    31  		if e.Timeout() {
    32  			statusCode = http.StatusGatewayTimeout
    33  		} else {
    34  			statusCode = http.StatusBadGateway
    35  		}
    36  	} else if err == io.EOF {
    37  		statusCode = http.StatusBadGateway
    38  	} else if err == context.Canceled {
    39  		statusCode = StatusClientClosedRequest
    40  	}
    41  
    42  	w.WriteHeader(statusCode)
    43  	w.Write([]byte(statusText(statusCode))) // nolint errcheck
    44  }
    45  
    46  func statusText(statusCode int) string {
    47  
    48  	prefix := http.StatusText(statusCode)
    49  
    50  	switch statusCode {
    51  	case http.StatusGatewayTimeout:
    52  		return prefix + TriremeGatewayTimeout
    53  	case http.StatusBadGateway:
    54  		return prefix + TriremeBadGatewayText
    55  	case StatusClientClosedRequest:
    56  		return StatusClientClosedRequestText
    57  	}
    58  	return prefix
    59  }