简体   繁体   中英

Check if value is typeof struct

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.

  1. How can I use a type switch for any (mgo) struct?
  2. How do I cast this struct before I can use it with JSON.Marshall?

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)))
    }
}
  • Have 2 different functions, one for structs and one for native types, this is the cleanest / most efficient way.
  • 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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM