當前位置: 首頁>>代碼示例>>Golang>>正文


Golang json.RawMessage函數代碼示例

本文整理匯總了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")
	}

}
開發者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, &params, &resp); err != nil {
			log.Fatal(err)
		}
		fmt.Println(string(resp))
	} else {
		rd := c.Stream(serviceMethod, &params)
		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


注:本文中的encoding/json.RawMessage函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。