Skip to content

refactor: remove errors package #43

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

Merged
merged 3 commits into from
Jun 2, 2023
Merged
Show file tree
Hide file tree
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
52 changes: 23 additions & 29 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,32 +78,34 @@ func (c *Context) QueryParams() url.Values {
return c.request.URL.Query()
}

// mustWrite writes raw bytes to the response.
func (c *Context) mustWrite(blob []byte) {
if _, err := c.Response().Write(blob); err != nil {
panic(err)
}
}

// JSON sends JSON response with the given status code.
//
// Returns an error if an error happened during sending response otherwise returns nil.
func (c *Context) JSON(code int, obj any) error {
func (c *Context) JSON(code int, obj any) {
c.writeContentType("application/json")
c.response.WriteHeader(code)
return c.kid.jsonSerializer.Write(c.Response(), obj, "")
c.kid.jsonSerializer.Write(c.Response(), obj, "")
}

// JSONIndent sends JSON response with the given status code.
// Sends response with the given indent.
//
// Returns an error if an error happened during sending response otherwise returns nil.
func (c *Context) JSONIndent(code int, obj any, indent string) error {
func (c *Context) JSONIndent(code int, obj any, indent string) {
c.writeContentType("application/json")
c.response.WriteHeader(code)
return c.kid.jsonSerializer.Write(c.Response(), obj, indent)
c.kid.jsonSerializer.Write(c.Response(), obj, indent)
}

// JSONByte sends JSON response with the given status code.
// Writes JSON blob untouched to response.
func (c *Context) JSONByte(code int, blob []byte) error {
func (c *Context) JSONByte(code int, blob []byte) {
c.writeContentType("application/json")
c.response.WriteHeader(code)
_, err := c.Response().Write(blob)
return err
c.mustWrite(blob)
}

// ReadJSON reads request's body as JSON and stores it in the given object.
Expand All @@ -115,29 +117,26 @@ func (c *Context) ReadJSON(out any) error {
// XML sends XML response with the given status code.
//
// Returns an error if an error happened during sending response otherwise returns nil.
func (c *Context) XML(code int, obj any) error {
func (c *Context) XML(code int, obj any) {
c.writeContentType("application/xml")
c.response.WriteHeader(code)
return c.kid.xmlSerializer.Write(c.Response(), obj, "")
c.kid.xmlSerializer.Write(c.Response(), obj, "")
}

// XMLIndent sends XML response with the given status code.
// Sends response with the given indent.
//
// Returns an error if an error happened during sending response otherwise returns nil.
func (c *Context) XMLIndent(code int, obj any, indent string) error {
func (c *Context) XMLIndent(code int, obj any, indent string) {
c.writeContentType("application/xml")
c.response.WriteHeader(code)
return c.kid.xmlSerializer.Write(c.Response(), obj, indent)
c.kid.xmlSerializer.Write(c.Response(), obj, indent)
}

// XMLByte sends XML response with the given status code.
// Writes JSON blob untouched to response.
func (c *Context) XMLByte(code int, blob []byte) error {
func (c *Context) XMLByte(code int, blob []byte) {
c.writeContentType("application/xml")
c.response.WriteHeader(code)
_, err := c.Response().Write(blob)
return err
c.mustWrite(blob)
}

// ReadXML reads request's body as XML and stores it in the given object.
Expand All @@ -150,22 +149,17 @@ func (c *Context) ReadXML(out any) error {
//
// tpl must be a relative path to templates root directory.
// Defaults to "templates/".
//
// Returns an error if an error happened during sending response otherwise returns nil.
func (c *Context) HTML(code int, tpl string, data any) error {
func (c *Context) HTML(code int, tpl string, data any) {
c.writeContentType("text/html")
c.response.WriteHeader(code)
return c.kid.htmlRenderer.RenderHTML(c.Response(), tpl, data)
c.kid.htmlRenderer.RenderHTML(c.Response(), tpl, data)
}

// HTMLString sends bare string as HTML response with the given status code.
//
// Returns an error if an error happened during sending response otherwise returns nil.
func (c *Context) HTMLString(code int, tpl string) error {
func (c *Context) HTMLString(code int, tpl string) {
c.writeContentType("text/html")
c.response.WriteHeader(code)
_, err := c.Response().Write([]byte(tpl))
return err
c.mustWrite([]byte(tpl))
}

// NoContent returns an empty response with the given status code.
Expand Down
96 changes: 50 additions & 46 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package kid
import (
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"net/http"
"net/http/httptest"
Expand All @@ -11,11 +12,18 @@ import (
"strings"
"testing"

"github.com/mojixcoder/kid/errors"
htmlrenderer "github.com/mojixcoder/kid/html_renderer"
"github.com/stretchr/testify/assert"
)

type errWriter struct {
*httptest.ResponseRecorder
}

func (errWriter) Write(blob []byte) (int, error) {
return 0, errors.New("new err")
}

type person struct {
Name string `json:"name" xml:"name"`
Age int `json:"age" xml:"age"`
Expand Down Expand Up @@ -238,11 +246,26 @@ func TestContext_ReadJSON(t *testing.T) {
ctx.reset(req, res)

var p2 person
httpErr := ctx.ReadJSON(&p2).(*errors.HTTPError)
err = ctx.ReadJSON(&p2)

assert.Error(t, err)
}

func TestContext_mustWrite(t *testing.T) {
ctx := newContext(New())

res := httptest.NewRecorder()
ctx.reset(nil, res)

ctx.mustWrite([]byte("byte"))

assert.Equal(t, "byte", res.Body.String())

ctx.reset(nil, errWriter{res})

assert.Error(t, httpErr)
assert.Error(t, httpErr.Err)
assert.Equal(t, http.StatusBadRequest, httpErr.Code)
assert.Panics(t, func() {
ctx.mustWrite([]byte("byte"))
})
}

func TestContext_JSON(t *testing.T) {
Expand All @@ -253,9 +276,8 @@ func TestContext_JSON(t *testing.T) {
ctx.reset(nil, res)

p := person{Name: "foo", Age: 1999}
err := ctx.JSON(http.StatusCreated, &p)
ctx.JSON(http.StatusCreated, &p)

assert.NoError(t, err)
assert.Equal(t, http.StatusCreated, res.Code)
assert.Equal(t, "application/json", res.Header().Get("Content-Type"))
assert.Equal(t, "{\"name\":\"foo\",\"age\":1999}\n", res.Body.String())
Expand All @@ -264,11 +286,9 @@ func TestContext_JSON(t *testing.T) {

ctx.reset(nil, res)

httpErr := ctx.JSON(http.StatusCreated, make(chan bool)).(*errors.HTTPError)

assert.Error(t, httpErr)
assert.Error(t, httpErr.Err)
assert.Equal(t, http.StatusInternalServerError, httpErr.Code)
assert.Panics(t, func() {
ctx.JSON(http.StatusCreated, make(chan bool))
})
}

func TestContext_JSONIndent(t *testing.T) {
Expand All @@ -279,9 +299,8 @@ func TestContext_JSONIndent(t *testing.T) {
ctx.reset(nil, res)

p := person{Name: "foo", Age: 1999}
err := ctx.JSONIndent(http.StatusCreated, &p, " ")
ctx.JSONIndent(http.StatusCreated, &p, " ")

assert.NoError(t, err)
assert.Equal(t, http.StatusCreated, res.Code)
assert.Equal(t, "application/json", res.Header().Get("Content-Type"))
assert.Equal(t, "{\n \"name\": \"foo\",\n \"age\": 1999\n}\n", res.Body.String())
Expand All @@ -290,11 +309,9 @@ func TestContext_JSONIndent(t *testing.T) {

ctx.reset(nil, res)

httpErr := ctx.JSONIndent(http.StatusCreated, make(chan bool), " ").(*errors.HTTPError)

assert.Error(t, httpErr)
assert.Error(t, httpErr.Err)
assert.Equal(t, http.StatusInternalServerError, httpErr.Code)
assert.Panics(t, func() {
ctx.JSONIndent(http.StatusCreated, make(chan bool), " ")
})
}

func TestContext_JSONByte(t *testing.T) {
Expand All @@ -309,9 +326,8 @@ func TestContext_JSONByte(t *testing.T) {
blob, err := json.Marshal(p)
assert.NoError(t, err)

err = ctx.JSONByte(http.StatusOK, blob)
ctx.JSONByte(http.StatusOK, blob)

assert.NoError(t, err)
assert.Equal(t, http.StatusOK, res.Code)
assert.Equal(t, "application/json", res.Header().Get("Content-Type"))
assert.Equal(t, "{\"name\":\"foo\",\"age\":1999}", res.Body.String())
Expand All @@ -335,11 +351,9 @@ func TestContext_ReadXML(t *testing.T) {
ctx.reset(req, nil)

var p2 person
httpErr := ctx.ReadXML(&p2).(*errors.HTTPError)
err = ctx.ReadXML(&p2)

assert.Error(t, httpErr)
assert.Error(t, httpErr.Err)
assert.Equal(t, http.StatusBadRequest, httpErr.Code)
assert.Error(t, err)
}

func TestContext_XML(t *testing.T) {
Expand All @@ -350,9 +364,8 @@ func TestContext_XML(t *testing.T) {
ctx.reset(nil, res)

p := person{Name: "foo", Age: 1999}
err := ctx.XML(http.StatusCreated, &p)
ctx.XML(http.StatusCreated, &p)

assert.NoError(t, err)
assert.Equal(t, http.StatusCreated, res.Code)
assert.Equal(t, "application/xml", res.Header().Get("Content-Type"))
assert.Equal(t, "<person><name>foo</name><age>1999</age></person>", res.Body.String())
Expand All @@ -361,11 +374,9 @@ func TestContext_XML(t *testing.T) {

ctx.reset(nil, res)

httpErr := ctx.XML(http.StatusCreated, make(chan bool)).(*errors.HTTPError)

assert.Error(t, httpErr)
assert.Error(t, httpErr.Err)
assert.Equal(t, http.StatusInternalServerError, httpErr.Code)
assert.Panics(t, func() {
ctx.XML(http.StatusCreated, make(chan bool))
})
}

func TestContext_XMLIndent(t *testing.T) {
Expand All @@ -376,9 +387,8 @@ func TestContext_XMLIndent(t *testing.T) {
ctx.reset(nil, res)

p := person{Name: "foo", Age: 1999}
err := ctx.XMLIndent(http.StatusCreated, &p, " ")
ctx.XMLIndent(http.StatusCreated, &p, " ")

assert.NoError(t, err)
assert.Equal(t, http.StatusCreated, res.Code)
assert.Equal(t, "application/xml", res.Header().Get("Content-Type"))
assert.Equal(t, "<person>\n <name>foo</name>\n <age>1999</age>\n</person>", res.Body.String())
Expand All @@ -387,11 +397,9 @@ func TestContext_XMLIndent(t *testing.T) {

ctx.reset(nil, res)

httpErr := ctx.XMLIndent(http.StatusCreated, make(chan bool), " ").(*errors.HTTPError)

assert.Error(t, httpErr)
assert.Error(t, httpErr.Err)
assert.Equal(t, http.StatusInternalServerError, httpErr.Code)
assert.Panics(t, func() {
ctx.XMLIndent(http.StatusCreated, make(chan bool), " ")
})
}

func TestContext_XMLByte(t *testing.T) {
Expand All @@ -406,9 +414,8 @@ func TestContext_XMLByte(t *testing.T) {
blob, err := xml.Marshal(p)
assert.NoError(t, err)

err = ctx.XMLByte(http.StatusOK, blob)
ctx.XMLByte(http.StatusOK, blob)

assert.NoError(t, err)
assert.Equal(t, http.StatusOK, res.Code)
assert.Equal(t, "application/xml", res.Header().Get("Content-Type"))
assert.Equal(t, "<person><name>foo</name><age>1999</age></person>", res.Body.String())
Expand All @@ -425,15 +432,14 @@ func TestContext_HTML(t *testing.T) {
res := httptest.NewRecorder()
ctx.reset(nil, res)

err := ctx.HTML(http.StatusAccepted, "index.html", nil)
ctx.HTML(http.StatusAccepted, "index.html", nil)

newLine := getNewLineStr()
expectedRes := fmt.Sprintf(
"%s<html><body>%s<p>content</p>%s</body></html>%s",
newLine, newLine, newLine, newLine,
)

assert.NoError(t, err)
assert.Equal(t, http.StatusAccepted, res.Code)
assert.Equal(t, expectedRes, res.Body.String())
assert.Equal(t, "text/html", res.Header().Get("Content-Type"))
Expand All @@ -445,11 +451,9 @@ func TestContext_HTMLString(t *testing.T) {
res := httptest.NewRecorder()
ctx.reset(nil, res)

err := ctx.HTMLString(http.StatusAccepted, "<p>Hello</p>")
ctx.HTMLString(http.StatusAccepted, "<p>Hello</p>")

assert.NoError(t, err)
assert.Equal(t, http.StatusAccepted, res.Code)
assert.Equal(t, "<p>Hello</p>", res.Body.String())
assert.Equal(t, "text/html", res.Header().Get("Content-Type"))

}
54 changes: 0 additions & 54 deletions errors/errors.go

This file was deleted.

Loading