traefik/vendor/github.com/vulcand/oxy/cbreaker/fallback.go

85 lines
2.1 KiB
Go
Raw Normal View History

2017-02-07 21:33:23 +00:00
package cbreaker
import (
"fmt"
"net/http"
"net/url"
"strconv"
2017-11-22 17:20:03 +00:00
log "github.com/Sirupsen/logrus"
"github.com/vulcand/oxy/utils"
2017-02-07 21:33:23 +00:00
)
type Response struct {
StatusCode int
ContentType string
Body []byte
}
type ResponseFallback struct {
r Response
}
func NewResponseFallback(r Response) (*ResponseFallback, error) {
if r.StatusCode == 0 {
return nil, fmt.Errorf("response code should not be 0")
}
return &ResponseFallback{r: r}, nil
}
func (f *ResponseFallback) ServeHTTP(w http.ResponseWriter, req *http.Request) {
2017-11-22 17:20:03 +00:00
if log.GetLevel() >= log.DebugLevel {
logEntry := log.WithField("Request", utils.DumpHttpRequest(req))
logEntry.Debug("vulcand/oxy/fallback/response: begin ServeHttp on request")
defer logEntry.Debug("vulcand/oxy/fallback/response: competed ServeHttp on request")
}
2017-02-07 21:33:23 +00:00
if f.r.ContentType != "" {
w.Header().Set("Content-Type", f.r.ContentType)
}
w.Header().Set("Content-Length", strconv.Itoa(len(f.r.Body)))
w.WriteHeader(f.r.StatusCode)
2017-11-22 17:20:03 +00:00
_, err := w.Write(f.r.Body)
if err != nil {
log.Errorf("vulcand/oxy/fallback/response: failed to write response, err: %v", err)
}
2017-02-07 21:33:23 +00:00
}
type Redirect struct {
2017-11-22 17:20:03 +00:00
URL string
PreservePath bool
2017-02-07 21:33:23 +00:00
}
type RedirectFallback struct {
u *url.URL
2017-11-22 17:20:03 +00:00
r Redirect
2017-02-07 21:33:23 +00:00
}
func NewRedirectFallback(r Redirect) (*RedirectFallback, error) {
u, err := url.ParseRequestURI(r.URL)
if err != nil {
return nil, err
}
2017-11-22 17:20:03 +00:00
return &RedirectFallback{u: u, r: r}, nil
2017-02-07 21:33:23 +00:00
}
func (f *RedirectFallback) ServeHTTP(w http.ResponseWriter, req *http.Request) {
2017-11-22 17:20:03 +00:00
if log.GetLevel() >= log.DebugLevel {
logEntry := log.WithField("Request", utils.DumpHttpRequest(req))
logEntry.Debug("vulcand/oxy/fallback/redirect: begin ServeHttp on request")
defer logEntry.Debug("vulcand/oxy/fallback/redirect: competed ServeHttp on request")
}
location := f.u.String()
if f.r.PreservePath {
location += req.URL.Path
}
w.Header().Set("Location", location)
2017-02-07 21:33:23 +00:00
w.WriteHeader(http.StatusFound)
2017-11-22 17:20:03 +00:00
_, err := w.Write([]byte(http.StatusText(http.StatusFound)))
if err != nil {
log.Errorf("vulcand/oxy/fallback/redirect: failed to write response, err: %v", err)
}
2017-02-07 21:33:23 +00:00
}