Reputation: 15752
I want to implement a Send
method on Context
which writes the given Object to the http.ResponseWriter
.
At the moment I have:
package context
import (
"net/http"
)
type Context struct {
Request *http.Request
ResponseWriter http.ResponseWriter
}
type Handle func(*Context)
func New(w http.ResponseWriter, r *http.Request) *Context {
return &Context{r, w}
}
func (c *Context) Send(value interface{}, code int) {
c.WriteHeader(code)
switch v := value.(type) {
case string:
c.Write(byte(value))
//default:
//json, err := json.Marshal(value)
//if err != nil {
// c.WriteHeader(http.StatusInternalServerError)
// c.Write([]byte(err.Error()))
//}
//c.Write([]byte(json))
}
}
func (c *Context) WriteHeader(code int) {
c.ResponseWriter.WriteHeader(code)
}
func (c *Context) Write(chunk []byte) {
c.ResponseWriter.Write(chunk)
}
As you see I commented something out so the program compiles. What I want to do in that section is to support custom structs which should be transformed to JSON for me.
Upvotes: 1
Views: 74
Reputation: 99274
You really should know your types, however you have 3 options.
Example :
func (c *Context) Send(value interface{}, code int) {
c.WriteHeader(code)
v := reflect.ValueOf(value)
if v.Kind() == reflect.Struct || v.Kind() == reflect.Ptr && v.Elem().Kind() == reflect.Struct {
json, err := json.Marshal(value)
if err != nil {
c.WriteHeader(http.StatusInternalServerError)
c.Write([]byte(err.Error()))
break
}
c.Write([]byte(json))
} else {
c.Write([]byte(fmt.Sprintf("%v", value)))
}
}
select
all native types and handle them then use default like you already.Example:
func (c *Context) Send(value interface{}, code int) {
c.WriteHeader(code)
switch v := value.(type) {
case string:
c.Write([]byte(v))
case byte, rune, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64,
float32, float64:
c.Write([]byte(fmt.Sprintf("%v", v)))
default: //everything else just encode as json
json, err := json.Marshal(value)
if err != nil {
c.WriteHeader(http.StatusInternalServerError)
c.Write([]byte(err.Error()))
break
}
c.Write(json) //json is already []byte, check http://golang.org/pkg/encoding/json/#Marshal
}
}
Upvotes: 2