本文整理汇总了Golang中encoding/json.RawMessage函数的典型用法代码示例。如果您正苦于以下问题:Golang RawMessage函数的具体用法?Golang RawMessage怎么用?Golang RawMessage使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了RawMessage函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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")
}
}
开发者ID:zofuthan,项目名称:containerbuddy,代码行数:28,代码来源:config_test.go
示例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)
}
开发者ID:alexsacr,项目名称:linode,代码行数:26,代码来源:marshal_test.go
示例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")
}
}
开发者ID:zofuthan,项目名称:containerbuddy,代码行数:28,代码来源:ips_test.go
示例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
}
开发者ID:pa001024,项目名称:reflex,代码行数:36,代码来源:WebQQ.content.go
示例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
}
开发者ID:logan,项目名称:heim,代码行数:33,代码来源:grants.go
示例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,
}
}
开发者ID:andremendonca,项目名称:centrifugo,代码行数:26,代码来源:client.go
示例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
}
开发者ID:ming-hai,项目名称:appmsgsrv,代码行数:58,代码来源:admin.go
示例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)
}
开发者ID:powerman,项目名称:rpc-codec,代码行数:49,代码来源:server.go
示例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)
}
}
开发者ID:ingresso-group,项目名称:rpc,代码行数:30,代码来源:json_test.go
示例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
}
开发者ID:qmdx,项目名称:gopush-cluster,代码行数:29,代码来源:mysql.go
示例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
}
开发者ID:Cl0udPhish,项目名称:go-swagger,代码行数:27,代码来源:expander.go
示例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
}
开发者ID:the-information,项目名称:ori,代码行数:35,代码来源:load.go
示例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
}
开发者ID:thechriswalker,项目名称:opfs,代码行数:28,代码来源:indexer_elasticsearch.go
示例14: RoutingInfo
func (l AppRoutes) RoutingInfo() receptor.RoutingInfo {
data, _ := json.Marshal(l)
routingInfo := json.RawMessage(data)
return receptor.RoutingInfo{
AppRouter: &routingInfo,
}
}
开发者ID:davidwadden,项目名称:lattice-release,代码行数:7,代码来源:route_helpers.go
示例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))
}
}
}
开发者ID:linearregression,项目名称:shipshape,代码行数:29,代码来源:example.go
示例16: broadcast
func (rb *RoomBinding) broadcast(
ctx scope.Context, db gorp.SqlExecutor, packetType proto.PacketType, payload interface{}, exclude ...proto.Session) error {
encodedPayload, err := json.Marshal(payload)
if err != nil {
return err
}
packet := &proto.Packet{Type: packetType, Data: json.RawMessage(encodedPayload)}
broadcastMsg := BroadcastMessage{
Event: packet,
Exclude: make([]string, 0, len(exclude)),
}
if rb != nil {
broadcastMsg.Room = rb.RoomName
}
for _, s := range exclude {
if s != nil {
broadcastMsg.Exclude = append(broadcastMsg.Exclude, s.ID())
}
}
encoded, err := json.Marshal(broadcastMsg)
if err != nil {
return err
}
escaped := strings.Replace(string(encoded), "'", "''", -1)
_, err = db.Exec(fmt.Sprintf("NOTIFY broadcast, '%s'", escaped))
return err
}
开发者ID:logan,项目名称:heim,代码行数:31,代码来源:room.go
示例17: TestVia
func TestVia(t *testing.T) {
t.Parallel()
canonicalKey := http.CanonicalHeaderKey("via")
var testText = "notnedomi 2.2"
v, err := New(config.NewHandler("via", json.RawMessage(`{"text": "notnedomi 2.2"}`)), nil,
testStringHandler(t, testText))
if err != nil {
t.Errorf("Got error when initializing via - %s", err)
}
var expect, got []string
recorder := httptest.NewRecorder()
v.RequestHandle(nil, recorder, nil)
expect = []string{testText}
got = recorder.Header()[canonicalKey]
if !reflect.DeepEqual(got, expect) {
t.Errorf("expected via header to be equal to %s but got %s", expect, got)
}
recorder.Header().Set(canonicalKey, "holla")
expect = []string{"holla", testText}
v.RequestHandle(nil, recorder, nil)
got = recorder.Header()[canonicalKey]
if !reflect.DeepEqual(got, expect) {
t.Errorf("expected via header to be equal to %s but got %s", expect, got)
}
}
开发者ID:na--,项目名称:nedomi,代码行数:27,代码来源:via_test.go
示例18: Read
// ReadFrame decodes the next JSON object in the stream, or returns an error. The returned
// byte slice will be modified the next time ReadFrame is invoked and should not be altered.
func (r *jsonFrameReader) Read(data []byte) (int, error) {
// Return whatever remaining data exists from an in progress frame
if n := len(r.remaining); n > 0 {
if n <= len(data) {
data = append(data[0:0], r.remaining...)
r.remaining = nil
return n, nil
}
n = len(data)
data = append(data[0:0], r.remaining[:n]...)
r.remaining = r.remaining[n:]
return n, io.ErrShortBuffer
}
// RawMessage#Unmarshal appends to data - we reset the slice down to 0 and will either see
// data written to data, or be larger than data and a different array.
n := len(data)
m := json.RawMessage(data[:0])
if err := r.decoder.Decode(&m); err != nil {
return 0, err
}
// If capacity of data is less than length of the message, decoder will allocate a new slice
// and set m to it, which means we need to copy the partial result back into data and preserve
// the remaining result for subsequent reads.
if len(m) > n {
data = append(data[0:0], m[:n]...)
r.remaining = m[n:]
return n, io.ErrShortBuffer
}
return len(m), nil
}
开发者ID:Cloven,项目名称:minikube,代码行数:35,代码来源:framer.go
示例19: CreateRequestMessage
// CreateRequestMessage creates the request json message using the given input.
// Note, the input *MUST* be a pointer to a valid backend type that this
// client recognises.
func (cs *ClientServerImpl) CreateRequestMessage(input interface{}) ([]byte, error) {
msg := &RequestMessage{}
recognizedTypes := cs.GetRecognizedTypes()
for typeStr, typeVal := range recognizedTypes {
if reflect.TypeOf(input) == reflect.PtrTo(typeVal) {
msg.Type = typeStr
break
}
}
if msg.Type == "" {
return nil, &UnrecognizedWSRequestType{reflect.TypeOf(input).String()}
}
messageData, err := jsonutil.BuildJSON(input)
if err != nil {
return nil, &NotMarshallableWSRequest{msg.Type, err}
}
msg.Message = json.RawMessage(messageData)
send, err := json.Marshal(msg)
if err != nil {
return nil, &NotMarshallableWSRequest{msg.Type, err}
}
return send, nil
}
开发者ID:appuri,项目名称:amazon-ecs-agent,代码行数:28,代码来源:client.go
示例20: TestUnmarshalSingleBool
func TestUnmarshalSingleBool(t *testing.T) {
// doesn't currently get exercised in normal usage
var out bool
err := unmarshalSingle(json.RawMessage([]byte(`{"foo": true}`)), "foo", &out)
require.NoError(t, err)
assert.True(t, out)
}
开发者ID:alexsacr,项目名称:linode,代码行数:7,代码来源:marshal_test.go
注:本文中的encoding/json.RawMessage函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论