Skip to content

Commit

Permalink
Handle error.
Browse files Browse the repository at this point in the history
  • Loading branch information
googollee committed Apr 11, 2024
1 parent 6033697 commit ab29eaf
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 18 deletions.
17 changes: 0 additions & 17 deletions endpoint.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
package espresso

import "net/http"

type EndpointBuilder interface {
BindPath(key string, v any) EndpointBuilder
End() BindErrors
Expand All @@ -25,18 +23,3 @@ func newEndpoint() *Endpoint {
HeadParams: make(map[string]BindParam),
}
}

func (e *Endpoint) serveHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != e.Method {
http.NotFound(w, r)
return
}

ctx := &runtimeContext{
ctx: r.Context(),
endpoint: e,
request: r,
response: w,
}
ctx.Next()
}
24 changes: 23 additions & 1 deletion router.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,28 @@ func (g *router) register(ctx *buildtimeContext, fn HandleFunc) {

pattern := ctx.endpoint.Method + " " + path
g.mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
endpoint.serveHTTP(w, r)
wr := &responseWriter{
ResponseWriter: w,
}

ctx := &runtimeContext{
ctx: r.Context(),
endpoint: &endpoint,
request: r,
response: wr,
}

ctx.Next()

if wr.hasWritten || ctx.err != nil {
return
}

code := http.StatusInternalServerError
if httpCoder, ok := ctx.err.(HTTPError); ok {
code = httpCoder.HTTPCode()
}
w.WriteHeader(code)
fmt.Fprint(w, ctx.err.Error())
})
}
1 change: 1 addition & 0 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ func (s *Espresso) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err != nil {
panic(err)
}

r = r.WithContext(ctx)
s.mux.ServeHTTP(w, r)
}

0 comments on commit ab29eaf

Please sign in to comment.