From 90f8e82f1447def6279d82b09c7e9fa21e0d9e15 Mon Sep 17 00:00:00 2001 From: yusing Date: Fri, 28 Mar 2025 07:30:32 +0800 Subject: [PATCH] refactor: error http handling --- internal/api/v1/homepage_overrides.go | 18 +++++++------- internal/api/v1/index.go | 4 +-- internal/api/v1/list.go | 35 ++++++++++++++------------- internal/api/v1/reload.go | 6 ++--- internal/api/v1/stats.go | 18 ++++++++------ internal/api/v1/version.go | 4 +-- internal/entrypoint/entrypoint.go | 8 +++--- 7 files changed, 48 insertions(+), 45 deletions(-) diff --git a/internal/api/v1/homepage_overrides.go b/internal/api/v1/homepage_overrides.go index 0d570fb..6c3d303 100644 --- a/internal/api/v1/homepage_overrides.go +++ b/internal/api/v1/homepage_overrides.go @@ -5,8 +5,8 @@ import ( "io" "net/http" - "github.com/yusing/go-proxy/internal/api/v1/utils" "github.com/yusing/go-proxy/internal/homepage" + "github.com/yusing/go-proxy/internal/net/gphttp" ) const ( @@ -37,13 +37,13 @@ type ( func SetHomePageOverrides(w http.ResponseWriter, r *http.Request) { what := r.FormValue("what") if what == "" { - http.Error(w, "missing what or which", http.StatusBadRequest) + gphttp.BadRequest(w, "missing what or which") return } data, err := io.ReadAll(r.Body) if err != nil { - utils.RespondError(w, err, http.StatusBadRequest) + gphttp.ClientError(w, err, http.StatusBadRequest) return } r.Body.Close() @@ -53,32 +53,32 @@ func SetHomePageOverrides(w http.ResponseWriter, r *http.Request) { case HomepageOverrideItem: var params HomepageOverrideItemParams if err := json.Unmarshal(data, ¶ms); err != nil { - utils.RespondError(w, err, http.StatusBadRequest) + gphttp.ClientError(w, err, http.StatusBadRequest) return } overrides.OverrideItem(params.Which, ¶ms.Value) case HomepageOverrideItemsBatch: var params HomepageOverrideItemsBatchParams if err := json.Unmarshal(data, ¶ms); err != nil { - utils.RespondError(w, err, http.StatusBadRequest) + gphttp.ClientError(w, err, http.StatusBadRequest) return } overrides.OverrideItems(params.Value) case HomepageOverrideItemVisible: // POST /v1/item_visible [a,b,c], false => hide a, b, c var params HomepageOverrideItemVisibleParams if err := json.Unmarshal(data, ¶ms); err != nil { - utils.RespondError(w, err, http.StatusBadRequest) + gphttp.ClientError(w, err, http.StatusBadRequest) return } if params.Value { - overrides.UnhideItems(params.Which...) + overrides.UnhideItems(params.Which) } else { - overrides.HideItems(params.Which...) + overrides.HideItems(params.Which) } case HomepageOverrideCategoryOrder: var params HomepageOverrideCategoryOrderParams if err := json.Unmarshal(data, ¶ms); err != nil { - utils.RespondError(w, err, http.StatusBadRequest) + gphttp.ClientError(w, err, http.StatusBadRequest) return } overrides.SetCategoryOrder(params.Which, params.Value) diff --git a/internal/api/v1/index.go b/internal/api/v1/index.go index 71bbf2e..dcaa976 100644 --- a/internal/api/v1/index.go +++ b/internal/api/v1/index.go @@ -3,9 +3,9 @@ package v1 import ( "net/http" - . "github.com/yusing/go-proxy/internal/api/v1/utils" + "github.com/yusing/go-proxy/internal/net/gphttp" ) func Index(w http.ResponseWriter, r *http.Request) { - WriteBody(w, []byte("API ready")) + gphttp.WriteBody(w, []byte("API ready")) } diff --git a/internal/api/v1/list.go b/internal/api/v1/list.go index d45ffc4..ecbce0d 100644 --- a/internal/api/v1/list.go +++ b/internal/api/v1/list.go @@ -1,15 +1,16 @@ package v1 import ( + "fmt" "net/http" "strconv" "strings" "github.com/yusing/go-proxy/internal" - U "github.com/yusing/go-proxy/internal/api/v1/utils" "github.com/yusing/go-proxy/internal/common" config "github.com/yusing/go-proxy/internal/config/types" - "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" "github.com/yusing/go-proxy/internal/route/routes/routequery" route "github.com/yusing/go-proxy/internal/route/types" "github.com/yusing/go-proxy/internal/task" @@ -43,24 +44,24 @@ func List(cfg config.ConfigInstance, w http.ResponseWriter, r *http.Request) { if route == nil { http.NotFound(w, r) } else { - U.RespondJSON(w, r, route) + gphttp.RespondJSON(w, r, route) } case ListRoutes: - U.RespondJSON(w, r, routequery.RoutesByAlias(route.RouteType(r.FormValue("type")))) + gphttp.RespondJSON(w, r, routequery.RoutesByAlias(route.RouteType(r.FormValue("type")))) case ListFiles: listFiles(w, r) case ListMiddlewares: - U.RespondJSON(w, r, middleware.All()) + gphttp.RespondJSON(w, r, middleware.All()) case ListMiddlewareTraces: - U.RespondJSON(w, r, middleware.GetAllTrace()) + gphttp.RespondJSON(w, r, middleware.GetAllTrace()) case ListMatchDomains: - U.RespondJSON(w, r, cfg.Value().MatchDomains) + gphttp.RespondJSON(w, r, cfg.Value().MatchDomains) case ListHomepageConfig: - U.RespondJSON(w, r, routequery.HomepageConfig(cfg.Value().Homepage.UseDefaultCategories, r.FormValue("category"), r.FormValue("provider"))) + gphttp.RespondJSON(w, r, routequery.HomepageConfig(r.FormValue("category"), r.FormValue("provider"))) case ListRouteProviders: - U.RespondJSON(w, r, cfg.RouteProviderList()) + gphttp.RespondJSON(w, r, cfg.RouteProviderList()) case ListHomepageCategories: - U.RespondJSON(w, r, routequery.HomepageCategories()) + gphttp.RespondJSON(w, r, routequery.HomepageCategories()) case ListIcons: limit, err := strconv.Atoi(r.FormValue("limit")) if err != nil { @@ -68,17 +69,17 @@ func List(cfg config.ConfigInstance, w http.ResponseWriter, r *http.Request) { } icons, err := internal.SearchIcons(r.FormValue("keyword"), limit) if err != nil { - U.RespondError(w, err) + gphttp.ClientError(w, err) return } if icons == nil { icons = []string{} } - U.RespondJSON(w, r, icons) + gphttp.RespondJSON(w, r, icons) case ListTasks: - U.RespondJSON(w, r, task.DebugTaskList()) + gphttp.RespondJSON(w, r, task.DebugTaskList()) default: - U.HandleErr(w, r, U.ErrInvalidKey("what"), http.StatusBadRequest) + gphttp.BadRequest(w, fmt.Sprintf("invalid what: %s", what)) } } @@ -99,7 +100,7 @@ func listRoute(which string) any { func listFiles(w http.ResponseWriter, r *http.Request) { files, err := utils.ListFiles(common.ConfigBasePath, 0, true) if err != nil { - U.HandleErr(w, r, err) + gphttp.ServerError(w, r, err) return } resp := map[FileType][]string{ @@ -116,12 +117,12 @@ func listFiles(w http.ResponseWriter, r *http.Request) { mids, err := utils.ListFiles(common.MiddlewareComposeBasePath, 0, true) if err != nil { - U.HandleErr(w, r, err) + gphttp.ServerError(w, r, err) return } for _, mid := range mids { mid = strings.TrimPrefix(mid, common.MiddlewareComposeBasePath+"/") resp[FileTypeMiddleware] = append(resp[FileTypeMiddleware], mid) } - U.RespondJSON(w, r, resp) + gphttp.RespondJSON(w, r, resp) } diff --git a/internal/api/v1/reload.go b/internal/api/v1/reload.go index defa4e4..1460d47 100644 --- a/internal/api/v1/reload.go +++ b/internal/api/v1/reload.go @@ -3,14 +3,14 @@ package v1 import ( "net/http" - U "github.com/yusing/go-proxy/internal/api/v1/utils" config "github.com/yusing/go-proxy/internal/config/types" + "github.com/yusing/go-proxy/internal/net/gphttp" ) func Reload(cfg config.ConfigInstance, w http.ResponseWriter, r *http.Request) { if err := cfg.Reload(); err != nil { - U.HandleErr(w, r, err) + gphttp.ServerError(w, r, err) return } - U.WriteBody(w, []byte("OK")) + gphttp.WriteBody(w, []byte("OK")) } diff --git a/internal/api/v1/stats.go b/internal/api/v1/stats.go index e86c8de..1fbac51 100644 --- a/internal/api/v1/stats.go +++ b/internal/api/v1/stats.go @@ -6,19 +6,21 @@ import ( "github.com/coder/websocket" "github.com/coder/websocket/wsjson" - U "github.com/yusing/go-proxy/internal/api/v1/utils" config "github.com/yusing/go-proxy/internal/config/types" + "github.com/yusing/go-proxy/internal/net/gphttp" + "github.com/yusing/go-proxy/internal/net/gphttp/gpwebsocket" + "github.com/yusing/go-proxy/internal/net/gphttp/httpheaders" "github.com/yusing/go-proxy/internal/utils/strutils" ) func Stats(cfg config.ConfigInstance, w http.ResponseWriter, r *http.Request) { - U.RespondJSON(w, r, getStats(cfg)) -} - -func StatsWS(cfg config.ConfigInstance, w http.ResponseWriter, r *http.Request) { - U.PeriodicWS(cfg, w, r, 1*time.Second, func(conn *websocket.Conn) error { - return wsjson.Write(r.Context(), conn, getStats(cfg)) - }) + if httpheaders.IsWebsocket(r.Header) { + gpwebsocket.Periodic(w, r, 1*time.Second, func(conn *websocket.Conn) error { + return wsjson.Write(r.Context(), conn, getStats(cfg)) + }) + } else { + gphttp.RespondJSON(w, r, getStats(cfg)) + } } var startTime = time.Now() diff --git a/internal/api/v1/version.go b/internal/api/v1/version.go index f0db6bf..f43a9d6 100644 --- a/internal/api/v1/version.go +++ b/internal/api/v1/version.go @@ -3,10 +3,10 @@ package v1 import ( "net/http" - . "github.com/yusing/go-proxy/internal/api/v1/utils" + "github.com/yusing/go-proxy/internal/net/gphttp" "github.com/yusing/go-proxy/pkg" ) func GetVersion(w http.ResponseWriter, r *http.Request) { - WriteBody(w, []byte(pkg.GetVersion())) + gphttp.WriteBody(w, []byte(pkg.GetVersion())) } diff --git a/internal/entrypoint/entrypoint.go b/internal/entrypoint/entrypoint.go index 3ab6dac..1a3a166 100644 --- a/internal/entrypoint/entrypoint.go +++ b/internal/entrypoint/entrypoint.go @@ -7,10 +7,10 @@ import ( "strings" "github.com/yusing/go-proxy/internal/logging" - gphttp "github.com/yusing/go-proxy/internal/net/http" - "github.com/yusing/go-proxy/internal/net/http/accesslog" - "github.com/yusing/go-proxy/internal/net/http/middleware" - "github.com/yusing/go-proxy/internal/net/http/middleware/errorpage" + gphttp "github.com/yusing/go-proxy/internal/net/gphttp" + "github.com/yusing/go-proxy/internal/net/gphttp/accesslog" + "github.com/yusing/go-proxy/internal/net/gphttp/middleware" + "github.com/yusing/go-proxy/internal/net/gphttp/middleware/errorpage" "github.com/yusing/go-proxy/internal/route/routes" route "github.com/yusing/go-proxy/internal/route/types" "github.com/yusing/go-proxy/internal/task"