go-chi / go-chi/render

render.Render() writes to writer unexpected data of aliased type

Open
#56 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
339
Forks
66
PR merge metrics
No merged PRs in 30d

Description

Hello,
During my work I faced unexpected behaviour on calling `render.Render()` when I was implemented Renderer interface on struct, which occured to be alias. Honestly, I have no clue why it's happening.
But it appears that render calls implicitly some default renderer IN ADDITION to my implementation.
It seems like it should exit [here](https://github.com/go-chi/render/blob/master/render.go#L69) but it does not.
```go
package main

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

"github.com/go-chi/render"
)

type (
PublicProfile Profile
Profile struct {
Name string
Age int
}
ProfileResponse struct {
Name string `json:"name"`
}
)

func (p PublicProfile) Render(w http.ResponseWriter, rq *http.Request) error {
render.Status(rq, http.StatusNoContent)
render.JSON(w, rq, ProfileResponse{Name: p.Name})
return nil
}

func main() {
w := httptest.NewRecorder()
rq := httptest.NewRequest(http.MethodGet, "/", nil)
someProfile := Profile{Name: "John", Age: 42}
wrappedProfile := PublicProfile(someProfile)
render.Render(w, rq, wrappedProfile)
responseBody, _ := io.ReadAll(w.Body)
fmt.Println(w.Code, string(responseBody))
}
```
Output:
```bash
204 {"name":"John"}
{"Name":"John","Age":42}
```
[On go-playground](https://go.dev/play/p/GaIPhxRqjVz)

The only way around I have found is setting default responder to empty func. Is this expected way to it?
```go
render.Respond = func(w http.ResponseWriter, rq *http.Request, v interface{}) {}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.