package methodsallowed_test import ( "io" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/require" "go.xsfx.dev/somehttphandlers/methodsallowed" ) var handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { //nolint:gochecknoglobals if _, err := io.WriteString(w, "hello world"); err != nil { w.WriteHeader(http.StatusInternalServerError) return } }) func TestAllow(t *testing.T) { t.Parallel() tables := []struct { method string body string statusCode int }{ { http.MethodGet, "hello world", http.StatusOK, }, { http.MethodDelete, "Method not allowed\n", http.StatusMethodNotAllowed, }, } // Only allow GET and POST. allow := methodsallowed.Allow(http.MethodGet, http.MethodPost)(handler) for _, table := range tables { table := table t.Run(table.method, func(t *testing.T) { t.Parallel() req := httptest.NewRequest(table.method, "/", nil) w := httptest.NewRecorder() allow.ServeHTTP(w, req) resp := w.Result() defer resp.Body.Close() body, _ := io.ReadAll(resp.Body) require.Equal(t, table.body, string(body)) require.Equal(t, table.statusCode, resp.StatusCode) }) } } func TestNotAllow(t *testing.T) { t.Parallel() }