refactor: rename module 'err' to 'gperr' and use gphttp error handling

This commit is contained in:
yusing 2025-03-28 07:14:34 +08:00
parent 3021672de5
commit 4a2cc70b52
7 changed files with 59 additions and 63 deletions

View file

@ -17,7 +17,7 @@ import (
"github.com/yusing/go-proxy/internal/api/v1/query" "github.com/yusing/go-proxy/internal/api/v1/query"
"github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/common"
"github.com/yusing/go-proxy/internal/config" "github.com/yusing/go-proxy/internal/config"
E "github.com/yusing/go-proxy/internal/error" "github.com/yusing/go-proxy/internal/gperr"
"github.com/yusing/go-proxy/internal/homepage" "github.com/yusing/go-proxy/internal/homepage"
"github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/logging"
"github.com/yusing/go-proxy/internal/net/http/middleware" "github.com/yusing/go-proxy/internal/net/http/middleware"
@ -47,7 +47,7 @@ func main() {
switch args.Command { switch args.Command {
case common.CommandReload: case common.CommandReload:
if err := query.ReloadServer(); err != nil { if err := query.ReloadServer(); err != nil {
E.LogFatal("server reload error", err) gperr.LogFatal("server reload error", err)
} }
rawLogger.Println("ok") rawLogger.Println("ok")
return return
@ -107,9 +107,9 @@ func main() {
middleware.LoadComposeFiles() middleware.LoadComposeFiles()
var cfg *config.Config var cfg *config.Config
var err E.Error var err gperr.Error
if cfg, err = config.Load(); err != nil { if cfg, err = config.Load(); err != nil {
E.LogWarn("errors in config", err) gperr.LogWarn("errors in config", err)
} }
switch args.Command { switch args.Command {

View file

@ -3,9 +3,8 @@ package auth
import ( import (
"net/http" "net/http"
U "github.com/yusing/go-proxy/internal/api/v1/utils"
"github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/common"
"github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/net/gphttp"
) )
var defaultAuth Provider var defaultAuth Provider
@ -13,7 +12,6 @@ var defaultAuth Provider
// Initialize sets up authentication providers. // Initialize sets up authentication providers.
func Initialize() error { func Initialize() error {
if !IsEnabled() { if !IsEnabled() {
logging.Warn().Msg("authentication is disabled, please set API_JWT_SECRET or OIDC_* to enable authentication")
return nil return nil
} }
@ -44,7 +42,7 @@ func RequireAuth(next http.HandlerFunc) http.HandlerFunc {
if IsEnabled() { if IsEnabled() {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
if err := defaultAuth.CheckToken(r); err != nil { if err := defaultAuth.CheckToken(r); err != nil {
U.RespondError(w, err, http.StatusUnauthorized) gphttp.ClientError(w, err, http.StatusUnauthorized)
} else { } else {
next(w, r) next(w, r)
} }

View file

@ -12,10 +12,9 @@ import (
"time" "time"
"github.com/coreos/go-oidc/v3/oidc" "github.com/coreos/go-oidc/v3/oidc"
U "github.com/yusing/go-proxy/internal/api/v1/utils"
"github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/common"
E "github.com/yusing/go-proxy/internal/error" "github.com/yusing/go-proxy/internal/net/gphttp"
CE "github.com/yusing/go-proxy/internal/utils" "github.com/yusing/go-proxy/internal/utils"
"github.com/yusing/go-proxy/internal/utils/strutils" "github.com/yusing/go-proxy/internal/utils/strutils"
"golang.org/x/oauth2" "golang.org/x/oauth2"
) )
@ -131,9 +130,9 @@ func (auth *OIDCProvider) CheckToken(r *http.Request) error {
// Logical AND between allowed users and groups. // Logical AND between allowed users and groups.
allowedUser := slices.Contains(auth.allowedUsers, claims.Username) allowedUser := slices.Contains(auth.allowedUsers, claims.Username)
allowedGroup := len(CE.Intersect(claims.Groups, auth.allowedGroups)) > 0 allowedGroup := len(utils.Intersect(claims.Groups, auth.allowedGroups)) > 0
if !allowedUser && !allowedGroup { if !allowedUser && !allowedGroup {
return ErrUserNotAllowed.Subject(claims.Username) return ErrUserNotAllowed
} }
return nil return nil
} }
@ -154,7 +153,7 @@ func generateState() (string, error) {
func (auth *OIDCProvider) RedirectLoginPage(w http.ResponseWriter, r *http.Request) { func (auth *OIDCProvider) RedirectLoginPage(w http.ResponseWriter, r *http.Request) {
state, err := generateState() state, err := generateState()
if err != nil { if err != nil {
U.HandleErr(w, r, err, http.StatusInternalServerError) gphttp.ServerError(w, r, err)
return return
} }
http.SetCookie(w, &http.Cookie{ http.SetCookie(w, &http.Cookie{
@ -171,7 +170,7 @@ func (auth *OIDCProvider) RedirectLoginPage(w http.ResponseWriter, r *http.Reque
if auth.isMiddleware { if auth.isMiddleware {
u, err := r.URL.Parse(redirURL) u, err := r.URL.Parse(redirURL)
if err != nil { if err != nil {
U.HandleErr(w, r, err, http.StatusInternalServerError) gphttp.ServerError(w, r, err)
return return
} }
q := u.Query() q := u.Query()
@ -201,31 +200,31 @@ func (auth *OIDCProvider) LoginCallbackHandler(w http.ResponseWriter, r *http.Re
state, err := r.Cookie(CookieOauthState) state, err := r.Cookie(CookieOauthState)
if err != nil { if err != nil {
U.HandleErr(w, r, E.New("missing state cookie"), http.StatusBadRequest) gphttp.BadRequest(w, "missing state cookie")
return return
} }
query := r.URL.Query() query := r.URL.Query()
if query.Get("state") != state.Value { if query.Get("state") != state.Value {
U.HandleErr(w, r, E.New("invalid oauth state"), http.StatusBadRequest) gphttp.BadRequest(w, "invalid oauth state")
return return
} }
oauth2Token, err := auth.exchange(r) oauth2Token, err := auth.exchange(r)
if err != nil { if err != nil {
U.HandleErr(w, r, fmt.Errorf("failed to exchange token: %w", err), http.StatusInternalServerError) gphttp.ServerError(w, r, fmt.Errorf("failed to exchange token: %w", err))
return return
} }
rawIDToken, ok := oauth2Token.Extra("id_token").(string) rawIDToken, ok := oauth2Token.Extra("id_token").(string)
if !ok { if !ok {
U.HandleErr(w, r, E.New("missing id_token"), http.StatusInternalServerError) gphttp.BadRequest(w, "missing id_token")
return return
} }
idToken, err := auth.oidcVerifier.Verify(r.Context(), rawIDToken) idToken, err := auth.oidcVerifier.Verify(r.Context(), rawIDToken)
if err != nil { if err != nil {
U.HandleErr(w, r, fmt.Errorf("failed to verify ID token: %w", err), http.StatusInternalServerError) gphttp.ServerError(w, r, fmt.Errorf("failed to verify ID token: %w", err))
return return
} }
@ -243,7 +242,7 @@ func (auth *OIDCProvider) LogoutCallbackHandler(w http.ResponseWriter, r *http.R
token, err := r.Cookie(auth.TokenCookieName()) token, err := r.Cookie(auth.TokenCookieName())
if err != nil { if err != nil {
U.HandleErr(w, r, E.New("missing token cookie"), http.StatusBadRequest) gphttp.BadRequest(w, "missing token cookie")
return return
} }
clearTokenCookie(w, r, auth.TokenCookieName()) clearTokenCookie(w, r, auth.TokenCookieName())
@ -258,12 +257,12 @@ func (auth *OIDCProvider) LogoutCallbackHandler(w http.ResponseWriter, r *http.R
func (auth *OIDCProvider) handleTestCallback(w http.ResponseWriter, r *http.Request) { func (auth *OIDCProvider) handleTestCallback(w http.ResponseWriter, r *http.Request) {
state, err := r.Cookie(CookieOauthState) state, err := r.Cookie(CookieOauthState)
if err != nil { if err != nil {
U.HandleErr(w, r, E.New("missing state cookie"), http.StatusBadRequest) gphttp.BadRequest(w, "missing state cookie")
return return
} }
if r.URL.Query().Get("state") != state.Value { if r.URL.Query().Get("state") != state.Value {
U.HandleErr(w, r, E.New("invalid oauth state"), http.StatusBadRequest) gphttp.BadRequest(w, "invalid oauth state")
return return
} }

View file

@ -7,16 +7,16 @@ import (
"time" "time"
"github.com/golang-jwt/jwt/v5" "github.com/golang-jwt/jwt/v5"
U "github.com/yusing/go-proxy/internal/api/v1/utils"
"github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/common"
E "github.com/yusing/go-proxy/internal/error" "github.com/yusing/go-proxy/internal/gperr"
"github.com/yusing/go-proxy/internal/net/gphttp"
"github.com/yusing/go-proxy/internal/utils/strutils" "github.com/yusing/go-proxy/internal/utils/strutils"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
var ( var (
ErrInvalidUsername = E.New("invalid username") ErrInvalidUsername = gperr.New("invalid username")
ErrInvalidPassword = E.New("invalid password") ErrInvalidPassword = gperr.New("invalid password")
) )
type ( type (
@ -94,7 +94,7 @@ func (auth *UserPassAuth) CheckToken(r *http.Request) error {
case claims.Username != auth.username: case claims.Username != auth.username:
return ErrUserNotAllowed.Subject(claims.Username) return ErrUserNotAllowed.Subject(claims.Username)
case claims.ExpiresAt.Before(time.Now()): case claims.ExpiresAt.Before(time.Now()):
return E.Errorf("token expired on %s", strutils.FormatTime(claims.ExpiresAt.Time)) return gperr.Errorf("token expired on %s", strutils.FormatTime(claims.ExpiresAt.Time))
} }
return nil return nil
@ -111,17 +111,16 @@ func (auth *UserPassAuth) LoginCallbackHandler(w http.ResponseWriter, r *http.Re
} }
err := json.NewDecoder(r.Body).Decode(&creds) err := json.NewDecoder(r.Body).Decode(&creds)
if err != nil { if err != nil {
U.HandleErr(w, r, err, http.StatusBadRequest) gphttp.Unauthorized(w, "invalid credentials")
return return
} }
if err := auth.validatePassword(creds.User, creds.Pass); err != nil { if err := auth.validatePassword(creds.User, creds.Pass); err != nil {
U.LogError(r).Err(err).Msg("auth: invalid credentials") gphttp.Unauthorized(w, "invalid credentials")
U.RespondError(w, E.New("invalid credentials"), http.StatusUnauthorized)
return return
} }
token, err := auth.NewToken() token, err := auth.NewToken()
if err != nil { if err != nil {
U.HandleErr(w, r, err, http.StatusInternalServerError) gphttp.ServerError(w, r, err)
return return
} }
setTokenCookie(w, r, auth.TokenCookieName(), token, auth.tokenTTL) setTokenCookie(w, r, auth.TokenCookieName(), token, auth.tokenTTL)

View file

@ -5,14 +5,14 @@ import (
"net/http" "net/http"
"time" "time"
E "github.com/yusing/go-proxy/internal/error" "github.com/yusing/go-proxy/internal/gperr"
"github.com/yusing/go-proxy/internal/utils/strutils" "github.com/yusing/go-proxy/internal/utils/strutils"
) )
var ( var (
ErrMissingToken = E.New("missing token") ErrMissingToken = gperr.New("missing token")
ErrInvalidToken = E.New("invalid token") ErrInvalidToken = gperr.New("invalid token")
ErrUserNotAllowed = E.New("user not allowed") ErrUserNotAllowed = gperr.New("user not allowed")
) )
// cookieFQDN returns the fully qualified domain name of the request host // cookieFQDN returns the fully qualified domain name of the request host

View file

@ -13,10 +13,10 @@ import (
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
"github.com/vincent-petithory/dataurl" "github.com/vincent-petithory/dataurl"
U "github.com/yusing/go-proxy/internal/api/v1/utils" "github.com/yusing/go-proxy/internal/gperr"
"github.com/yusing/go-proxy/internal/homepage" "github.com/yusing/go-proxy/internal/homepage"
"github.com/yusing/go-proxy/internal/logging" "github.com/yusing/go-proxy/internal/logging"
gphttp "github.com/yusing/go-proxy/internal/net/http" gphttp "github.com/yusing/go-proxy/internal/net/gphttp"
"github.com/yusing/go-proxy/internal/route/routes" "github.com/yusing/go-proxy/internal/route/routes"
route "github.com/yusing/go-proxy/internal/route/types" route "github.com/yusing/go-proxy/internal/route/types"
"github.com/yusing/go-proxy/internal/utils/strutils" "github.com/yusing/go-proxy/internal/utils/strutils"
@ -54,11 +54,11 @@ func (res *fetchResult) ContentType() string {
func GetFavIcon(w http.ResponseWriter, req *http.Request) { func GetFavIcon(w http.ResponseWriter, req *http.Request) {
url, alias := req.FormValue("url"), req.FormValue("alias") url, alias := req.FormValue("url"), req.FormValue("alias")
if url == "" && alias == "" { if url == "" && alias == "" {
U.RespondError(w, U.ErrMissingKey("url or alias"), http.StatusBadRequest) gphttp.ClientError(w, gphttp.ErrMissingKey("url or alias"), http.StatusBadRequest)
return return
} }
if url != "" && alias != "" { if url != "" && alias != "" {
U.RespondError(w, U.ErrInvalidKey("url and alias are mutually exclusive"), http.StatusBadRequest) gphttp.ClientError(w, gperr.New("url and alias are mutually exclusive"), http.StatusBadRequest)
return return
} }
@ -66,7 +66,7 @@ func GetFavIcon(w http.ResponseWriter, req *http.Request) {
if url != "" { if url != "" {
var iconURL homepage.IconURL var iconURL homepage.IconURL
if err := iconURL.Parse(url); err != nil { if err := iconURL.Parse(url); err != nil {
U.RespondError(w, err, http.StatusBadRequest) gphttp.ClientError(w, err, http.StatusBadRequest)
return return
} }
fetchResult := getFavIconFromURL(&iconURL) fetchResult := getFavIconFromURL(&iconURL)
@ -75,20 +75,20 @@ func GetFavIcon(w http.ResponseWriter, req *http.Request) {
return return
} }
w.Header().Set("Content-Type", fetchResult.ContentType()) w.Header().Set("Content-Type", fetchResult.ContentType())
U.WriteBody(w, fetchResult.icon) gphttp.WriteBody(w, fetchResult.icon)
return return
} }
// try with route.Homepage.Icon // try with route.Homepage.Icon
r, ok := routes.GetHTTPRoute(alias) r, ok := routes.GetHTTPRoute(alias)
if !ok { if !ok {
U.RespondError(w, errors.New("no such route"), http.StatusNotFound) gphttp.ClientError(w, errors.New("no such route"), http.StatusNotFound)
return return
} }
var result *fetchResult var result *fetchResult
hp := r.HomepageConfig().GetOverride() hp := r.HomepageItem()
if !hp.IsEmpty() && hp.Icon != nil { if hp.Icon != nil {
if hp.Icon.IconSource == homepage.IconSourceRelative { if hp.Icon.IconSource == homepage.IconSourceRelative {
result = findIcon(r, req, hp.Icon.Value) result = findIcon(r, req, hp.Icon.Value)
} else { } else {
@ -106,7 +106,7 @@ func GetFavIcon(w http.ResponseWriter, req *http.Request) {
return return
} }
w.Header().Set("Content-Type", result.ContentType()) w.Header().Set("Content-Type", result.ContentType())
U.WriteBody(w, result.icon) gphttp.WriteBody(w, result.icon)
} }
func getFavIconFromURL(iconURL *homepage.IconURL) *fetchResult { func getFavIconFromURL(iconURL *homepage.IconURL) *fetchResult {
@ -126,7 +126,7 @@ func fetchIconAbsolute(url string) *fetchResult {
return result return result
} }
resp, err := U.Get(url) resp, err := gphttp.Get(url)
if err != nil || resp.StatusCode != http.StatusOK { if err != nil || resp.StatusCode != http.StatusOK {
if err == nil { if err == nil {
err = errors.New(resp.Status) err = errors.New(resp.Status)
@ -191,7 +191,7 @@ func findIcon(r route.HTTPRoute, req *http.Request, uri string) *fetchResult {
result := fetchIcon("png", sanitizeName(r.TargetName())) result := fetchIcon("png", sanitizeName(r.TargetName()))
cont := r.ContainerInfo() cont := r.ContainerInfo()
if !result.OK() && cont != nil { if !result.OK() && cont != nil {
result = fetchIcon("png", sanitizeName(cont.ImageName)) result = fetchIcon("png", sanitizeName(cont.Image.Name))
} }
if !result.OK() { if !result.OK() {
// fallback to parse html // fallback to parse html

View file

@ -7,20 +7,20 @@ import (
"net/http" "net/http"
v1 "github.com/yusing/go-proxy/internal/api/v1" v1 "github.com/yusing/go-proxy/internal/api/v1"
U "github.com/yusing/go-proxy/internal/api/v1/utils"
"github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/common"
E "github.com/yusing/go-proxy/internal/error" "github.com/yusing/go-proxy/internal/gperr"
"github.com/yusing/go-proxy/internal/net/http/middleware" "github.com/yusing/go-proxy/internal/net/gphttp"
"github.com/yusing/go-proxy/internal/net/gphttp/middleware"
) )
func ReloadServer() E.Error { func ReloadServer() gperr.Error {
resp, err := U.Post(common.APIHTTPURL+"/v1/reload", "", nil) resp, err := gphttp.Post(common.APIHTTPURL+"/v1/reload", "", nil)
if err != nil { if err != nil {
return E.From(err) return gperr.Wrap(err)
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
failure := E.Errorf("server reload status %v", resp.StatusCode) failure := gperr.Errorf("server reload status %v", resp.StatusCode)
body, err := io.ReadAll(resp.Body) body, err := io.ReadAll(resp.Body)
if err != nil { if err != nil {
return failure.With(err) return failure.With(err)
@ -31,34 +31,34 @@ func ReloadServer() E.Error {
return nil return nil
} }
func List[T any](what string) (_ T, outErr E.Error) { func List[T any](what string) (_ T, outErr gperr.Error) {
resp, err := U.Get(fmt.Sprintf("%s/v1/list/%s", common.APIHTTPURL, what)) resp, err := gphttp.Get(fmt.Sprintf("%s/v1/list/%s", common.APIHTTPURL, what))
if err != nil { if err != nil {
outErr = E.From(err) outErr = gperr.Wrap(err)
return return
} }
defer resp.Body.Close() defer resp.Body.Close()
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
outErr = E.Errorf("list %s: failed, status %v", what, resp.StatusCode) outErr = gperr.Errorf("list %s: failed, status %v", what, resp.StatusCode)
return return
} }
var res T var res T
err = json.NewDecoder(resp.Body).Decode(&res) err = json.NewDecoder(resp.Body).Decode(&res)
if err != nil { if err != nil {
outErr = E.From(err) outErr = gperr.Wrap(err)
return return
} }
return res, nil return res, nil
} }
func ListRoutes() (map[string]map[string]any, E.Error) { func ListRoutes() (map[string]map[string]any, gperr.Error) {
return List[map[string]map[string]any](v1.ListRoutes) return List[map[string]map[string]any](v1.ListRoutes)
} }
func ListMiddlewareTraces() (middleware.Traces, E.Error) { func ListMiddlewareTraces() (middleware.Traces, gperr.Error) {
return List[middleware.Traces](v1.ListMiddlewareTraces) return List[middleware.Traces](v1.ListMiddlewareTraces)
} }
func DebugListTasks() (map[string]any, E.Error) { func DebugListTasks() (map[string]any, gperr.Error) {
return List[map[string]any](v1.ListTasks) return List[map[string]any](v1.ListTasks)
} }