Skip to content

Commit

Permalink
refactor(handler): clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
utilyre committed Nov 11, 2024
1 parent e879850 commit 422e917
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 11 deletions.
14 changes: 8 additions & 6 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,23 +5,25 @@ import (
"sync/atomic"
)

var defaultErrorHandler atomic.Value
var defaultEH atomic.Value

func init() {
defaultErrorHandler.Store(ErrorHandler(func(w http.ResponseWriter, r *http.Request, err error) {
_ = WriteText(w, http.StatusInternalServerError, err.Error())
}))
defaultEH.Store(ErrorHandler(handleError))
}

func handleError(w http.ResponseWriter, r *http.Request, err error) {
_ = WriteText(w, http.StatusInternalServerError, err.Error())
}

// Default returns the default error handler.
func Default() ErrorHandler {
return defaultErrorHandler.Load().(ErrorHandler)
return defaultEH.Load().(ErrorHandler)
}

// SetDefault sets the default error handler, which is used by top-level
// functions Handle and HandleFunc.
func SetDefault(eh ErrorHandler) {
defaultErrorHandler.Store(eh)
defaultEH.Store(eh)
}

// Handle calls Handle on the default error handler.
Expand Down
12 changes: 7 additions & 5 deletions handler_test.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package xmate
package xmate_test

import (
"io"
"net/http"
"net/http/httptest"
"testing"

"github.com/utilyre/xmate/v3"
)

func handleError(w http.ResponseWriter, r *http.Request, err error) {
_ = WriteText(w, http.StatusInternalServerError, err.Error())
_ = xmate.WriteText(w, http.StatusInternalServerError, err.Error())
}

func handleEcho(w http.ResponseWriter, r *http.Request) error {
Expand All @@ -18,7 +20,7 @@ func handleEcho(w http.ResponseWriter, r *http.Request) error {
}

if len(body) == 0 {
return WriteText(w, http.StatusBadRequest, "missing request body")
return xmate.WriteText(w, http.StatusBadRequest, "missing request body")
}

w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
Expand All @@ -28,11 +30,11 @@ func handleEcho(w http.ResponseWriter, r *http.Request) error {
}

func TestErrorHandler(t *testing.T) {
handler := ErrorHandler(handleError)
eh := xmate.ErrorHandler(handleError)

w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodPost, "/", nil)
handler.HandleFunc(handleEcho).ServeHTTP(w, r)
eh.HandleFunc(handleEcho).ServeHTTP(w, r)

resp := w.Result()
defer resp.Body.Close()
Expand Down

0 comments on commit 422e917

Please sign in to comment.