Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add utility methods that embedds fmt.Sprintf #12

Merged
merged 1 commit into from
Mar 17, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions httpstub.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"io"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -280,6 +281,16 @@ func (m *matcher) Path(path string) *matcher {
return m
}

// Pathf create request matcher using sprintf-ed path.
func (rt *Router) Pathf(format string, a ...any) *matcher {
return rt.Path(fmt.Sprintf(format, a...))
}

// Pathf append matcher using sprintf-ed path to request matcher.
func (m *matcher) Pathf(format string, a ...any) *matcher {
return m.Path(fmt.Sprintf(format, a...))
}

// DefaultMiddleware append default middleware.
func (rt *Router) DefaultMiddleware(mw func(next http.HandlerFunc) http.HandlerFunc) {
rt.mu.Lock()
Expand Down Expand Up @@ -322,12 +333,12 @@ func (m *matcher) Header(key, value string) *matcher {
return m
}

// Handler set hander.
// Handler set handler.
func (m *matcher) Handler(fn func(w http.ResponseWriter, r *http.Request)) {
m.handler = http.HandlerFunc(fn)
}

// Response set hander which return response.
// Response set handler which return response (status and body).
func (m *matcher) Response(status int, body []byte) {
fn := func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(status)
Expand All @@ -336,12 +347,18 @@ func (m *matcher) Response(status int, body []byte) {
m.handler = http.HandlerFunc(fn)
}

// ResponseString set hander which return response.
// ResponseString set handler which return response (status and string-body).
func (m *matcher) ResponseString(status int, body string) {
b := []byte(body)
m.Response(status, b)
}

// ResponseStringf set handler which return response (status and sprintf-ed-body).
func (m *matcher) ResponseStringf(status int, format string, a ...any) {
b := []byte(fmt.Sprintf(format, a...))
m.Response(status, b)
}

// Requests returns []*http.Request received by router.
func (rt *Router) Requests() []*http.Request {
rt.mu.RLock()
Expand Down