Implemented the io.Writer interface

This commit is contained in:
Eduard Urbach 2024-03-13 22:49:57 +01:00
parent c13dbc55d2
commit 80dc3f87eb
Signed by: akyoto
GPG Key ID: C874F672B1AF20C0
2 changed files with 12 additions and 0 deletions

View File

@ -26,6 +26,7 @@ type Context interface {
ResponseHeader(key string) string ResponseHeader(key string) string
Status(status int) Context Status(status int) Context
String(string) error String(string) error
Write([]byte) (int, error)
} }
// ctx represents a request & response context. // ctx represents a request & response context.
@ -142,6 +143,11 @@ func (ctx *ctx) String(body string) error {
return ctx.Bytes(slice) return ctx.Bytes(slice)
} }
// Write implements the io.Writer interface.
func (ctx *ctx) Write(body []byte) (int, error) {
return ctx.response.Write(body)
}
// addParameter adds a new parameter to the context. // addParameter adds a new parameter to the context.
func (ctx *ctx) addParameter(name string, value string) { func (ctx *ctx) addParameter(name string, value string) {
ctx.paramNames[ctx.paramCount] = name ctx.paramNames[ctx.paramCount] = name

View File

@ -26,6 +26,11 @@ func TestRouter(t *testing.T) {
return ctx.String("Hello") return ctx.String("Hello")
}) })
s.Get("/write", func(ctx server.Context) error {
_, err := io.WriteString(ctx, "Hello")
return err
})
s.Get("/error", func(ctx server.Context) error { s.Get("/error", func(ctx server.Context) error {
return ctx.Status(http.StatusUnauthorized).Error("Not logged in") return ctx.Status(http.StatusUnauthorized).Error("Not logged in")
}) })
@ -94,6 +99,7 @@ func TestRouter(t *testing.T) {
{Method: "GET", URL: "/response/header", Status: http.StatusOK, Body: "text/plain"}, {Method: "GET", URL: "/response/header", Status: http.StatusOK, Body: "text/plain"},
{Method: "GET", URL: "/reader", Status: http.StatusOK, Body: "Hello"}, {Method: "GET", URL: "/reader", Status: http.StatusOK, Body: "Hello"},
{Method: "GET", URL: "/string", Status: http.StatusOK, Body: "Hello"}, {Method: "GET", URL: "/string", Status: http.StatusOK, Body: "Hello"},
{Method: "GET", URL: "/write", Status: http.StatusOK, Body: "Hello"},
{Method: "GET", URL: "/blog/testing-my-router", Status: http.StatusOK, Body: "testing-my-router"}, {Method: "GET", URL: "/blog/testing-my-router", Status: http.StatusOK, Body: "testing-my-router"},
{Method: "GET", URL: "/missing-parameter", Status: http.StatusOK, Body: ""}, {Method: "GET", URL: "/missing-parameter", Status: http.StatusOK, Body: ""},
{Method: "POST", URL: "/", Status: http.StatusOK, Body: "Post"}, {Method: "POST", URL: "/", Status: http.StatusOK, Body: "Post"},