本文整理汇总了Golang中encoding/json.RawMessage函数的典型用法代码示例。如果您正苦于以下问题:Golang RawMessage函数的具体用法?Golang RawMessage怎么用?Golang RawMessage使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了RawMessage函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: TestParseCommandArgs
func TestParseCommandArgs(t *testing.T) {
if cmd, err := parseCommandArgs(nil); err == nil {
validateCommandParsed(t, "command", cmd, nil)
} else {
t.Errorf("Unexpected parse error: %s", err.Error())
}
expected := []string{"/test.sh", "arg1"}
json1 := json.RawMessage(`"/test.sh arg1"`)
if cmd, err := parseCommandArgs(json1); err == nil {
validateCommandParsed(t, "json1", cmd, expected)
} else {
t.Errorf("Unexpected parse error json1: %s", err.Error())
}
json2 := json.RawMessage(`["/test.sh","arg1"]`)
if cmd, err := parseCommandArgs(json2); err == nil {
validateCommandParsed(t, "json2", cmd, expected)
} else {
t.Errorf("Unexpected parse error json2: %s", err.Error())
}
json3 := json.RawMessage(`{ "a": true }`)
if _, err := parseCommandArgs(json3); err == nil {
t.Errorf("Expected parse error for json3")
}
}
示例2: TestUnmarshalSingleErrs
func TestUnmarshalSingleErrs(t *testing.T) {
err := unmarshalSingle(json.RawMessage{}, "", "foo")
assert.Error(t, err)
var foo string
err = unmarshalSingle(json.RawMessage([]byte(`{"bar":"baz"}`)), "foo", &foo)
assert.Error(t, err)
var outInt int
var outStr string
var outBool bool
var outSlice []struct{}
err = unmarshalSingle(json.RawMessage([]byte(`{"foo": "bar"}`)), "foo", &outInt)
assert.Error(t, err)
assert.Empty(t, outInt)
err = unmarshalSingle(json.RawMessage([]byte(`{"foo": 1}`)), "foo", &outStr)
assert.Error(t, err)
assert.Empty(t, outStr)
err = unmarshalSingle(json.RawMessage([]byte(`{"foo": "bar"}`)), "foo", &outBool)
assert.Error(t, err)
assert.Empty(t, outBool)
err = unmarshalSingle(json.RawMessage([]byte(`{"foo": "bar"}`)), "foo", &outSlice)
assert.Error(t, err)
assert.Empty(t, outSlice)
}
示例3: TestParseInterfaces
func TestParseInterfaces(t *testing.T) {
if interfaces, err := parseInterfaces(nil); err != nil {
t.Errorf("Unexpected parse error: %s", err.Error())
} else if len(interfaces) > 0 {
t.Errorf("Expected no interfaces, but got %s", interfaces)
}
json1 := json.RawMessage(`"eth0"`)
expected1 := []string{"eth0"}
if interfaces, err := parseInterfaces(json1); err != nil {
t.Errorf("Unexpected parse error: %s", err.Error())
} else if !reflect.DeepEqual(interfaces, expected1) {
t.Errorf("Expected %s, got: %s", expected1, interfaces)
}
json2 := json.RawMessage(`["ethwe","eth0"]`)
expected2 := []string{"ethwe", "eth0"}
if interfaces, err := parseInterfaces(json2); err != nil {
t.Errorf("Unexpected parse error: %s", err.Error())
} else if !reflect.DeepEqual(interfaces, expected2) {
t.Errorf("Expected %s, got: %s", expected2, interfaces)
}
json3 := json.RawMessage(`{ "a": true }`)
if _, err := parseInterfaces(json3); err == nil {
t.Errorf("Expected parse error for json3")
}
}
示例4: Encode
// 转换到下层对象
func (this ContentModel) Encode(webqq *WebQQ) (v Content) {
matches := contentPatten.FindAllStringSubmatch(this.Message, -1)
if matches == nil { // 没有图片
v = make([]json.RawMessage, 1, 2)
b, err := json.Marshal(this.Message)
util.Try(err)
v[0] = json.RawMessage(b)
} else {
v = make([]json.RawMessage, 0, len(matches)*2+2) // 123[]1[]2[]3 = 3*2+1 = 7
for _, v1 := range matches {
switch v1[1] {
case "offpic":
b, err := json.Marshal([]interface{}{v1[1], Offpic{Success: 1, FilePath: v1[2]}})
if err == nil {
v = append(v, b)
}
case "cface":
b, err := json.Marshal([]interface{}{v1[1], Cface{Key: webqq.cface_key, Name: v1[2], Server: DefaultServer}})
if err == nil {
v = append(v, json.RawMessage(b))
}
case "face":
b, err := json.Marshal([]interface{}{v1[1], util.ToInt(v1[2])})
if err == nil {
v = append(v, json.RawMessage(b))
}
}
}
}
b, err := json.Marshal([]interface{}{"font", this.Font})
util.Try(err)
v = append(v, json.RawMessage(b))
return v
}
示例5: Authority
func (gs *GrantManager) Authority(
ctx scope.Context, manager Account, managerKey *security.ManagedKey) (
subjectKeyPair *security.ManagedKeyPair, public, private *json.RawMessage, err error) {
managerKeyPair, err := manager.Unlock(managerKey)
if err != nil {
return nil, nil, nil, err
}
subjectKeyPair, err = gs.unlockSubjectKeyPair(ctx, manager, managerKeyPair)
if err != nil {
return nil, nil, nil, err
}
sourceCapability, err := gs.AccountCapability(ctx, manager)
if err != nil {
return nil, nil, nil, err
}
public = new(json.RawMessage)
if publicBytes := sourceCapability.PublicPayload(); publicBytes != nil {
*public = json.RawMessage(publicBytes)
}
private = new(json.RawMessage)
privateBytes, err := sourceCapability.DecryptPayload(gs.SubjectKeyPair, managerKeyPair)
if err != nil {
return nil, nil, nil, err
}
*private = json.RawMessage(privateBytes)
return
}
示例6: info
func (c *client) info(ch Channel) ClientInfo {
channelInfo, ok := c.channelInfo[ch]
if !ok {
channelInfo = []byte{}
}
var rawDefaultInfo *json.RawMessage
var rawChannelInfo *json.RawMessage
if len(c.defaultInfo) > 0 {
raw := json.RawMessage(c.defaultInfo)
rawDefaultInfo = &raw
} else {
rawDefaultInfo = nil
}
if len(channelInfo) > 0 {
raw := json.RawMessage(channelInfo)
rawChannelInfo = &raw
} else {
rawChannelInfo = nil
}
return ClientInfo{
User: c.User,
Client: c.UID,
DefaultInfo: rawDefaultInfo,
ChannelInfo: rawChannelInfo,
}
}
示例7: PushPrivate
// PushPrivate handle for push private message.
func PushPrivate(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method Not Allowed", 405)
return
}
body := ""
res := map[string]interface{}{"ret": app.OK}
defer app.RetPWrite(w, r, res, &body, time.Now())
// param
bodyBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
res["ret"] = app.ParamErr
logger.Errorf("ioutil.ReadAll() failed (%s)", err.Error())
return
}
body = string(bodyBytes)
params := r.URL.Query()
key := params.Get("key")
expireStr := params.Get("expire")
if key == "" {
res["ret"] = app.ParamErr
return
}
expire, err := strconv.ParseUint(expireStr, 10, 32)
if err != nil {
res["ret"] = app.ParamErr
logger.Errorf("strconv.ParseUint(\"%s\", 10, 32) error(%v)", expireStr, err)
return
}
node := myrpc.GetComet(key)
if node == nil || node.CometRPC == nil {
res["ret"] = app.NotFoundServer
return
}
client := node.CometRPC.Get()
if client == nil {
res["ret"] = app.NotFoundServer
return
}
rm := json.RawMessage(bodyBytes)
msg, err := rm.MarshalJSON()
if err != nil {
res["ret"] = app.ParamErr
logger.Errorf("json.RawMessage(\"%s\").MarshalJSON() error(%v)", body, err)
return
}
args := &myrpc.CometPushPrivateArgs{Msg: json.RawMessage(msg), Expire: uint(expire), Key: key}
ret := 0
if err := client.Call(myrpc.CometServicePushPrivate, args, &ret); err != nil {
logger.Errorf("client.Call(\"%s\", \"%v\", &ret) error(%v)", myrpc.CometServicePushPrivate, args, err)
res["ret"] = app.InternalErr
return
}
return
}
示例8: WriteResponse
func (c *serverCodec) WriteResponse(r *rpc.Response, x interface{}) error {
// If return error: nothing happens.
// In r.Error will be "" or .Error() of error returned by:
// - ReadRequestBody()
// - called RPC method
c.mutex.Lock()
b, ok := c.pending[r.Seq]
if !ok {
c.mutex.Unlock()
return errors.New("invalid sequence number in response")
}
delete(c.pending, r.Seq)
c.mutex.Unlock()
if replies, ok := x.(*[]*json.RawMessage); r.ServiceMethod == "JSONRPC2.Batch" && ok {
if len(*replies) == 0 {
return nil
}
c.encmutex.Lock()
defer c.encmutex.Unlock()
return c.enc.Encode(replies)
}
if b == nil {
// Notification. Do not respond.
return nil
}
resp := serverResponse{Version: "2.0", ID: b}
if r.Error == "" {
if x == nil {
resp.Result = &null
} else {
resp.Result = x
}
} else if r.Error[0] == '{' && r.Error[len(r.Error)-1] == '}' {
// Well… this check for '{'…'}' isn't too strict, but I
// suppose we're trusting our own RPC methods (this way they
// can force sending wrong reply or many replies instead
// of one) and normal errors won't be formatted this way.
raw := json.RawMessage(r.Error)
resp.Error = &raw
} else {
raw := json.RawMessage(newError(r.Error).Error())
resp.Error = &raw
}
c.encmutex.Lock()
defer c.encmutex.Unlock()
return c.enc.Encode(resp)
}
示例9: TestService
func TestService(t *testing.T) {
s := rpc.NewServer()
s.RegisterCodec(NewCodec(), "application/json")
s.RegisterService(new(Service1), "")
var res Service1Response
if err := execute(t, s, "Service1.Multiply", &Service1Request{4, 2}, &res); err != nil {
t.Error("Expected err to be nil, but got", err)
}
if res.Result != 8 {
t.Error("Expected res.Result to be 8, but got", res.Result)
}
if err := execute(t, s, "Service1.ResponseError", &Service1Request{4, 2}, &res); err == nil {
t.Errorf("Expected to get %q, but got nil", ErrResponseError)
} else if err.Error() != ErrResponseError.Error() {
t.Errorf("Expected to get %q, but got %q", ErrResponseError, err)
}
if code, res := executeRaw(t, s, json.RawMessage(`{"method":"Service1.Multiply","params":null,"id":5}`)); code != 400 {
t.Error("Expected response code to be 400, but got", code)
} else if v, ok := field("result", res.Bytes()); !ok || v != nil {
t.Errorf("Expected ok to be true and v to be nil, but got %v and %v", ok, v)
}
if err := execute(t, s, "Service1.ResponseJsonError", &Service1Request{4, 2}, &res); err == nil {
t.Errorf("Expected to get %q, but got nil", ErrResponseError)
} else if jsonErr, ok := err.(*Error); !ok {
t.Error("Expected err to be of a *json.Error type")
} else if !reflect.DeepEqual(jsonErr.Data, ErrResponseJsonError.Data) {
t.Errorf("Expected jsonErr to be %q, but got %q", ErrResponseJsonError, jsonErr)
}
}
示例10: GetPrivate
// GetPrivate implements the Storage GetPrivate method.
func (s *MySQLStorage) GetPrivate(key string, mid int64) ([]*myrpc.Message, error) {
db := s.getConn(key)
if db == nil {
return nil, ErrNoMySQLConn
}
now := time.Now().Unix()
rows, err := db.Query(getPrivateMsgSQL, key, mid)
if err != nil {
glog.Errorf("db.Query(\"%s\",\"%s\",%d,now) failed (%v)", getPrivateMsgSQL, key, mid, err)
return nil, err
}
expire := int64(0)
cmid := int64(0)
msg := json.RawMessage([]byte{})
msgs := []*myrpc.Message{}
for rows.Next() {
if err := rows.Scan(&cmid, &expire, &msg); err != nil {
glog.Errorf("rows.Scan() failed (%v)", err)
return nil, err
}
if now > expire {
glog.Warningf("user_key: \"%s\" mid: %d expired", key, cmid)
continue
}
msgs = append(msgs, &myrpc.Message{MsgId: cmid, GroupId: myrpc.PrivateGroupId, Msg: msg})
}
return msgs, nil
}
示例11: defaultSchemaLoader
func defaultSchemaLoader(root interface{}, ref *Ref, cache ResolutionCache) (*schemaLoader, error) {
if cache == nil {
cache = resCache
}
var ptr *jsonpointer.Pointer
if ref != nil {
ptr = ref.GetPointer()
}
currentRef := nextRef(root, ref, ptr)
return &schemaLoader{
root: root,
loadingRef: ref,
startingRef: ref,
cache: cache,
loadDoc: func(path string) (json.RawMessage, error) {
data, err := swag.LoadFromFileOrHTTP(path)
if err != nil {
return nil, err
}
return json.RawMessage(data), nil
},
currentRef: currentRef,
}, nil
}
示例12: flush
func flush(c *cli.Context, keys *[]string, values *[]json.RawMessage) error {
var buf bytes.Buffer
if _, err := buf.Write([]byte("{")); err != nil {
return err
}
for i, k := range *keys {
fmt.Fprintf(&buf, "\"%s\":", k)
if _, err := buf.Write((*values)[i]); err != nil {
return err
}
if i < len(*keys)-1 {
if _, err := buf.Write([]byte(",")); err != nil {
return err
}
}
}
if _, err := buf.Write([]byte("}")); err != nil {
return err
}
var src = json.RawMessage(buf.Bytes())
// send to admin
if err := post(c, "load", &src, nil); err != nil {
return err
}
// reset the key and value buffers
*keys = (*keys)[:0]
*values = (*values)[:0]
return nil
}
示例13: MarshalJSON
func (q *esQuery) MarshalJSON() ([]byte, error) {
var buff bytes.Buffer
//buff.Grow(queryWrapLength + len(filters) + len(sorts))
if q.allowDeleted == false {
q.filters = append(q.filters, json.RawMessage([]byte(`{"missing":{"field":"Deleted","existence":true,"null_value":true}}`)))
}
buff.Write(queryWrapPrefix)
if len(q.filters) > 0 {
filters, _ := json.Marshal(q.filters)
buff.Write(queryWrapFilterPrefix)
buff.Write(filters)
buff.Write(queryWrapObjectClose)
}
buff.Write(queryWrapObjectClose)
buff.Write(queryWrapObjectClose)
if len(q.sorts) > 0 {
sorts, _ := json.Marshal(q.sorts)
buff.Write(queryWrapSortPrefix)
buff.Write(sorts)
}
buff.Write(queryWrapObjectClose)
log.Println(buff.String())
return buff.Bytes(), nil
}
示例14: RoutingInfo
func (l AppRoutes) RoutingInfo() receptor.RoutingInfo {
data, _ := json.Marshal(l)
routingInfo := json.RawMessage(data)
return receptor.RoutingInfo{
AppRouter: &routingInfo,
}
}
示例15: main
func main() {
flag.Parse()
c := client.NewHTTPClient(*address)
if err := c.WaitUntilReady(*waitDuration); err != nil {
log.Fatal(err)
}
serviceMethod, params := flag.Arg(0), json.RawMessage(flag.Arg(1))
if *legacyCall {
var resp json.RawMessage
if err := c.Call(serviceMethod, ¶ms, &resp); err != nil {
log.Fatal(err)
}
fmt.Println(string(resp))
} else {
rd := c.Stream(serviceMethod, ¶ms)
defer rd.Close()
for {
var resp json.RawMessage
if err := rd.NextResult(&resp); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Println(string(resp))
}
}
}