Skip to content

Commit

Permalink
fix(proxy): support errors
Browse files Browse the repository at this point in the history
  • Loading branch information
OneOfOne committed Jun 5, 2024
1 parent 4748c9e commit 3085c90
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 5 deletions.
9 changes: 6 additions & 3 deletions proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ var hopHeaders = []string{
"Upgrade",
}

func ProxyHandler(host string, pathFn func(ctx *Context, path string) string) Handler {
func ProxyHandler(host string, pathFn func(ctx *Context, path string) (string, error)) Handler {
rp := &httputil.ReverseProxy{}

scheme := "http"
Expand Down Expand Up @@ -52,8 +52,11 @@ func ProxyHandler(host string, pathFn func(ctx *Context, path string) string) Ha

return func(ctx *Context) Response {
if pathFn != nil {
ctx.Path()
ctx.Req.URL.Path = pathFn(ctx, ctx.Req.URL.Path)
p, err := pathFn(ctx, ctx.Req.URL.Path)
if err != nil {
return NewJSONErrorResponse(http.StatusBadRequest, err)
}
ctx.Req.URL.Path = p
}

rp.ServeHTTP(ctx, ctx.Req)
Expand Down
4 changes: 2 additions & 2 deletions proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ func TestProxy(t *testing.T) {
s2 := newServerAndWait(t, "localhost:0")
defer s2.Shutdown(0)

s2.GET("/*fn", ProxyHandler(s.Addrs()[0], func(_ *Context, s string) string {
return "/api/" + s
s2.GET("/*fn", ProxyHandler(s.Addrs()[0], func(_ *Context, s string) (string, error) {
return "/api/" + s, nil
}))

http.Get("http://" + s2.Addrs()[0] + "/x")
Expand Down

0 comments on commit 3085c90

Please sign in to comment.