File: handler.go

package info (click to toggle)
golang-github-vulcand-oxy 2.0.0-3
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 728 kB
  • sloc: makefile: 14
file content (65 lines) | stat: -rw-r--r-- 1,720 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package utils

import (
	"context"
	"errors"
	"io"
	"net"
	"net/http"
)

// StatusClientClosedRequest non-standard HTTP status code for client disconnection.
const StatusClientClosedRequest = 499

// StatusClientClosedRequestText non-standard HTTP status for client disconnection.
const StatusClientClosedRequestText = "Client Closed Request"

// ErrorHandler error handler.
type ErrorHandler interface {
	ServeHTTP(w http.ResponseWriter, req *http.Request, err error)
}

// DefaultHandler default error handler.
var DefaultHandler ErrorHandler = &StdHandler{log: &NoopLogger{}}

// StdHandler Standard error handler.
type StdHandler struct {
	log Logger
}

func (e *StdHandler) ServeHTTP(w http.ResponseWriter, _ *http.Request, err error) {
	statusCode := http.StatusInternalServerError

	//nolint:errorlint // must be changed
	if e, ok := err.(net.Error); ok {
		if e.Timeout() {
			statusCode = http.StatusGatewayTimeout
		} else {
			statusCode = http.StatusBadGateway
		}
	} else if errors.Is(err, io.EOF) {
		statusCode = http.StatusBadGateway
	} else if errors.Is(err, context.Canceled) {
		statusCode = StatusClientClosedRequest
	}

	w.WriteHeader(statusCode)
	_, _ = w.Write([]byte(statusText(statusCode)))

	e.log.Debug("'%d %s' caused by: %v", statusCode, statusText(statusCode), err)
}

func statusText(statusCode int) string {
	if statusCode == StatusClientClosedRequest {
		return StatusClientClosedRequestText
	}
	return http.StatusText(statusCode)
}

// ErrorHandlerFunc error handler function type.
type ErrorHandlerFunc func(http.ResponseWriter, *http.Request, error)

// ServeHTTP calls f(w, r).
func (f ErrorHandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request, err error) {
	f(w, r, err)
}