refactor: error http handling

This commit is contained in:
yusing 2025-03-28 07:30:32 +08:00
parent 14bb66d12f
commit 90f8e82f14
7 changed files with 48 additions and 45 deletions

View file

@ -5,8 +5,8 @@ import (
"io" "io"
"net/http" "net/http"
"github.com/yusing/go-proxy/internal/api/v1/utils"
"github.com/yusing/go-proxy/internal/homepage" "github.com/yusing/go-proxy/internal/homepage"
"github.com/yusing/go-proxy/internal/net/gphttp"
) )
const ( const (
@ -37,13 +37,13 @@ type (
func SetHomePageOverrides(w http.ResponseWriter, r *http.Request) { func SetHomePageOverrides(w http.ResponseWriter, r *http.Request) {
what := r.FormValue("what") what := r.FormValue("what")
if what == "" { if what == "" {
http.Error(w, "missing what or which", http.StatusBadRequest) gphttp.BadRequest(w, "missing what or which")
return return
} }
data, err := io.ReadAll(r.Body) data, err := io.ReadAll(r.Body)
if err != nil { if err != nil {
utils.RespondError(w, err, http.StatusBadRequest) gphttp.ClientError(w, err, http.StatusBadRequest)
return return
} }
r.Body.Close() r.Body.Close()
@ -53,32 +53,32 @@ func SetHomePageOverrides(w http.ResponseWriter, r *http.Request) {
case HomepageOverrideItem: case HomepageOverrideItem:
var params HomepageOverrideItemParams var params HomepageOverrideItemParams
if err := json.Unmarshal(data, &params); err != nil { if err := json.Unmarshal(data, &params); err != nil {
utils.RespondError(w, err, http.StatusBadRequest) gphttp.ClientError(w, err, http.StatusBadRequest)
return return
} }
overrides.OverrideItem(params.Which, &params.Value) overrides.OverrideItem(params.Which, &params.Value)
case HomepageOverrideItemsBatch: case HomepageOverrideItemsBatch:
var params HomepageOverrideItemsBatchParams var params HomepageOverrideItemsBatchParams
if err := json.Unmarshal(data, &params); err != nil { if err := json.Unmarshal(data, &params); err != nil {
utils.RespondError(w, err, http.StatusBadRequest) gphttp.ClientError(w, err, http.StatusBadRequest)
return return
} }
overrides.OverrideItems(params.Value) overrides.OverrideItems(params.Value)
case HomepageOverrideItemVisible: // POST /v1/item_visible [a,b,c], false => hide a, b, c case HomepageOverrideItemVisible: // POST /v1/item_visible [a,b,c], false => hide a, b, c
var params HomepageOverrideItemVisibleParams var params HomepageOverrideItemVisibleParams
if err := json.Unmarshal(data, &params); err != nil { if err := json.Unmarshal(data, &params); err != nil {
utils.RespondError(w, err, http.StatusBadRequest) gphttp.ClientError(w, err, http.StatusBadRequest)
return return
} }
if params.Value { if params.Value {
overrides.UnhideItems(params.Which...) overrides.UnhideItems(params.Which)
} else { } else {
overrides.HideItems(params.Which...) overrides.HideItems(params.Which)
} }
case HomepageOverrideCategoryOrder: case HomepageOverrideCategoryOrder:
var params HomepageOverrideCategoryOrderParams var params HomepageOverrideCategoryOrderParams
if err := json.Unmarshal(data, &params); err != nil { if err := json.Unmarshal(data, &params); err != nil {
utils.RespondError(w, err, http.StatusBadRequest) gphttp.ClientError(w, err, http.StatusBadRequest)
return return
} }
overrides.SetCategoryOrder(params.Which, params.Value) overrides.SetCategoryOrder(params.Which, params.Value)

View file

@ -3,9 +3,9 @@ package v1
import ( import (
"net/http" "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) { func Index(w http.ResponseWriter, r *http.Request) {
WriteBody(w, []byte("API ready")) gphttp.WriteBody(w, []byte("API ready"))
} }

View file

@ -1,15 +1,16 @@
package v1 package v1
import ( import (
"fmt"
"net/http" "net/http"
"strconv" "strconv"
"strings" "strings"
"github.com/yusing/go-proxy/internal" "github.com/yusing/go-proxy/internal"
U "github.com/yusing/go-proxy/internal/api/v1/utils"
"github.com/yusing/go-proxy/internal/common" "github.com/yusing/go-proxy/internal/common"
config "github.com/yusing/go-proxy/internal/config/types" 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" "github.com/yusing/go-proxy/internal/route/routes/routequery"
route "github.com/yusing/go-proxy/internal/route/types" route "github.com/yusing/go-proxy/internal/route/types"
"github.com/yusing/go-proxy/internal/task" "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 { if route == nil {
http.NotFound(w, r) http.NotFound(w, r)
} else { } else {
U.RespondJSON(w, r, route) gphttp.RespondJSON(w, r, route)
} }
case ListRoutes: 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: case ListFiles:
listFiles(w, r) listFiles(w, r)
case ListMiddlewares: case ListMiddlewares:
U.RespondJSON(w, r, middleware.All()) gphttp.RespondJSON(w, r, middleware.All())
case ListMiddlewareTraces: case ListMiddlewareTraces:
U.RespondJSON(w, r, middleware.GetAllTrace()) gphttp.RespondJSON(w, r, middleware.GetAllTrace())
case ListMatchDomains: case ListMatchDomains:
U.RespondJSON(w, r, cfg.Value().MatchDomains) gphttp.RespondJSON(w, r, cfg.Value().MatchDomains)
case ListHomepageConfig: 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: case ListRouteProviders:
U.RespondJSON(w, r, cfg.RouteProviderList()) gphttp.RespondJSON(w, r, cfg.RouteProviderList())
case ListHomepageCategories: case ListHomepageCategories:
U.RespondJSON(w, r, routequery.HomepageCategories()) gphttp.RespondJSON(w, r, routequery.HomepageCategories())
case ListIcons: case ListIcons:
limit, err := strconv.Atoi(r.FormValue("limit")) limit, err := strconv.Atoi(r.FormValue("limit"))
if err != nil { 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) icons, err := internal.SearchIcons(r.FormValue("keyword"), limit)
if err != nil { if err != nil {
U.RespondError(w, err) gphttp.ClientError(w, err)
return return
} }
if icons == nil { if icons == nil {
icons = []string{} icons = []string{}
} }
U.RespondJSON(w, r, icons) gphttp.RespondJSON(w, r, icons)
case ListTasks: case ListTasks:
U.RespondJSON(w, r, task.DebugTaskList()) gphttp.RespondJSON(w, r, task.DebugTaskList())
default: 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) { func listFiles(w http.ResponseWriter, r *http.Request) {
files, err := utils.ListFiles(common.ConfigBasePath, 0, true) files, err := utils.ListFiles(common.ConfigBasePath, 0, true)
if err != nil { if err != nil {
U.HandleErr(w, r, err) gphttp.ServerError(w, r, err)
return return
} }
resp := map[FileType][]string{ resp := map[FileType][]string{
@ -116,12 +117,12 @@ func listFiles(w http.ResponseWriter, r *http.Request) {
mids, err := utils.ListFiles(common.MiddlewareComposeBasePath, 0, true) mids, err := utils.ListFiles(common.MiddlewareComposeBasePath, 0, true)
if err != nil { if err != nil {
U.HandleErr(w, r, err) gphttp.ServerError(w, r, err)
return return
} }
for _, mid := range mids { for _, mid := range mids {
mid = strings.TrimPrefix(mid, common.MiddlewareComposeBasePath+"/") mid = strings.TrimPrefix(mid, common.MiddlewareComposeBasePath+"/")
resp[FileTypeMiddleware] = append(resp[FileTypeMiddleware], mid) resp[FileTypeMiddleware] = append(resp[FileTypeMiddleware], mid)
} }
U.RespondJSON(w, r, resp) gphttp.RespondJSON(w, r, resp)
} }

View file

@ -3,14 +3,14 @@ package v1
import ( import (
"net/http" "net/http"
U "github.com/yusing/go-proxy/internal/api/v1/utils"
config "github.com/yusing/go-proxy/internal/config/types" 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) { func Reload(cfg config.ConfigInstance, w http.ResponseWriter, r *http.Request) {
if err := cfg.Reload(); err != nil { if err := cfg.Reload(); err != nil {
U.HandleErr(w, r, err) gphttp.ServerError(w, r, err)
return return
} }
U.WriteBody(w, []byte("OK")) gphttp.WriteBody(w, []byte("OK"))
} }

View file

@ -6,19 +6,21 @@ import (
"github.com/coder/websocket" "github.com/coder/websocket"
"github.com/coder/websocket/wsjson" "github.com/coder/websocket/wsjson"
U "github.com/yusing/go-proxy/internal/api/v1/utils"
config "github.com/yusing/go-proxy/internal/config/types" 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" "github.com/yusing/go-proxy/internal/utils/strutils"
) )
func Stats(cfg config.ConfigInstance, w http.ResponseWriter, r *http.Request) { func Stats(cfg config.ConfigInstance, w http.ResponseWriter, r *http.Request) {
U.RespondJSON(w, r, 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))
func StatsWS(cfg config.ConfigInstance, w http.ResponseWriter, r *http.Request) { })
U.PeriodicWS(cfg, w, r, 1*time.Second, func(conn *websocket.Conn) error { } else {
return wsjson.Write(r.Context(), conn, getStats(cfg)) gphttp.RespondJSON(w, r, getStats(cfg))
}) }
} }
var startTime = time.Now() var startTime = time.Now()

View file

@ -3,10 +3,10 @@ package v1
import ( import (
"net/http" "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" "github.com/yusing/go-proxy/pkg"
) )
func GetVersion(w http.ResponseWriter, r *http.Request) { func GetVersion(w http.ResponseWriter, r *http.Request) {
WriteBody(w, []byte(pkg.GetVersion())) gphttp.WriteBody(w, []byte(pkg.GetVersion()))
} }

View file

@ -7,10 +7,10 @@ import (
"strings" "strings"
"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/net/http/accesslog" "github.com/yusing/go-proxy/internal/net/gphttp/accesslog"
"github.com/yusing/go-proxy/internal/net/http/middleware" "github.com/yusing/go-proxy/internal/net/gphttp/middleware"
"github.com/yusing/go-proxy/internal/net/http/middleware/errorpage" "github.com/yusing/go-proxy/internal/net/gphttp/middleware/errorpage"
"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/task" "github.com/yusing/go-proxy/internal/task"