mirror of
https://github.com/hrfee/jfa-go.git
synced 2024-12-22 17:10:10 +00:00
Harvey Tindall
86c7551ff8
Added a new common.ConfigurableTransport interface which mediabrowser, ombi, jellyseer, discord, telegram and matrix (i.e. ThirdPartService/ContactMethodLinker) now all implement. proxies are bound to them in main.go, Email is still a special case (but from the previous commit, mailgun does use the proxy). mautrix/go has been updated, and context.TODO()s stuck everywhere since I still don't really comprehend why I should use them (FIXME literally).
80 lines
1.5 KiB
Go
80 lines
1.5 KiB
Go
package common
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"log"
|
|
"net/http"
|
|
|
|
lm "github.com/hrfee/jfa-go/logmessages"
|
|
)
|
|
|
|
// TimeoutHandler recovers from an http timeout or panic.
|
|
type TimeoutHandler func()
|
|
|
|
// NewTimeoutHandler returns a new Timeout handler.
|
|
func NewTimeoutHandler(name, addr string, noFail bool) TimeoutHandler {
|
|
return func() {
|
|
if r := recover(); r != nil {
|
|
out := fmt.Sprintf(lm.FailedAuth, name, addr, 0, lm.TimedOut)
|
|
if noFail {
|
|
log.Print(out)
|
|
} else {
|
|
log.Fatalf(out)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// most 404 errors are from UserNotFound, so this generic error doesn't really need any detail.
|
|
type ErrNotFound error
|
|
|
|
type ErrUnauthorized struct{}
|
|
|
|
func (err ErrUnauthorized) Error() string {
|
|
return lm.Unauthorized
|
|
}
|
|
|
|
type ErrForbidden struct{}
|
|
|
|
func (err ErrForbidden) Error() string {
|
|
return lm.Forbidden
|
|
}
|
|
|
|
var (
|
|
NotFound ErrNotFound = errors.New(lm.NotFound)
|
|
)
|
|
|
|
type ErrUnknown struct {
|
|
code int
|
|
}
|
|
|
|
func (err ErrUnknown) Error() string {
|
|
msg := fmt.Sprintf(lm.FailedGenericWithCode, err.code)
|
|
return msg
|
|
}
|
|
|
|
// GenericErr returns an error appropriate to the given HTTP status (or actual error, if given).
|
|
func GenericErr(status int, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
switch status {
|
|
case 200, 204, 201:
|
|
return nil
|
|
case 401, 400:
|
|
return ErrUnauthorized{}
|
|
case 404:
|
|
return NotFound
|
|
case 403:
|
|
return ErrForbidden{}
|
|
default:
|
|
return ErrUnknown{code: status}
|
|
}
|
|
}
|
|
|
|
type ConfigurableTransport interface {
|
|
// SetTransport sets the http.Transport to use for requests. Can be used to set a proxy.
|
|
SetTransport(t *http.Transport)
|
|
}
|