我想在Send
上实现Context
方法,将给定的对象写入http.ResponseWriter
。
目前我有:
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)
}
如你所见,我评论了一些内容,以便程序编译。我想在该部分中做的是支持自定义结构,应该为我转换为JSON。
答案 0 :(得分:2)
你真的应该知道你的类型,但你有3个选择。
示例:
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
所有原生类型并处理它们然后像你一样使用默认类型。示例:
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
}
}