在Golang中编码设置数据结构

I have a Set data structure implemented in Go with the basic operations like Add, Remove, Difference, Union. I am trying to send a http request using the json encoder to encode the request body which contains the object of the form map[string]Set. The Set data structure is defined below:

type Set map[interface{}]struct{}

func NewSet() Set {
    set := make(Set)
    return set
}

The encoder looks like this:

func (req *Request) BodyContentInJson (val interface{}) error {
    buf := bytes.NewBuffer(nil)
    enc := json.NewEncoder(buf)

    if err := enc.Encode(val); err != nil {
        return err
    }

    req.Obj = val
    req.Body = buf
    req.BodySize = int64(buf.Len())
    return nil
}

This code fails at

if err := enc.Encode(val); err != nil {
            return err
        }

giving an error:{"errors":["json: unsupported type: Set"]}. Also, the type of val is map[string]interface{}when I debugged it.

How could I possibly encode and marshal/unmarshal JSON content here using the Go's encoder ?

You could write your own UnmarshalJSON method on the *Set type which would then be used by the json.Encoder to encode the json data into the Set. Here's a simple example https://play.golang.org/p/kx1E-jDu5e.

By the way, the reason you're getting the error is because a map key of type interface{} is not supported by the encoding/json package. (https://github.com/golang/go/blob/master/src/encoding/json/encode.go#L697-L699)