Golang Marshal示例

说明

golang marshal示例是从最受好评的开源项目中提取的实现代码,你可以参考下面示例的使用方式。

编程语言: Golang

命名空间/包名称: encoding/json

示例#1
文件: auth.go 项目: CodeJuan/deis

// Regenerate user's auth tokens.
func Regenerate(c *client.Client, username string, all bool) (string, error) {
	var reqBody []byte
	var err error

	if all == true {
		reqBody, err = json.Marshal(api.AuthRegenerateRequest{All: all})
	} else if username != "" {
		reqBody, err = json.Marshal(api.AuthRegenerateRequest{Name: username})
	}

	if err != nil {
		return "", err
	}

	body, err := c.BasicRequest("POST", "/v1/auth/tokens/", reqBody)

	if err != nil {
		return "", err
	}

	if all == true {
		return "", nil
	}

	token := api.AuthRegenerateResponse{}
	if err = json.Unmarshal([]byte(body), &token); err != nil {
		return "", err
	}

	return token.Token, nil
}

示例#2
文件: incident.go 项目: postfix/bangarang

func (i *Incident) Get(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("content-type", "application/json")
	vars := mux.Vars(r)
	id, ok := vars["id"]
	if !ok {
		http.Error(w, "Must append incident id", http.StatusBadRequest)
		return
	}
	index := i.pipeline.GetIndex()

	// if the id is "*", fetch all outstanding incidents
	if id == "*" {
		all := index.ListIncidents()
		all = reduceStatusAbove(event.WARNING, all)
		buff, err := json.Marshal(makeKV(all))
		if err != nil {
			logrus.Error(err)
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Write(buff)
		return
	}

	// write out the found incident. The value will be null if nothing was found
	in := index.GetIncident([]byte(id))
	buff, err := json.Marshal(in)
	if err != nil {
		logrus.Error(err)
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Write(buff)
}

示例#3
文件: broker.go 项目: ntcong/sublime-text-2-config

func (b *Broker) SendNoLog(resp Response) error {
	b.wLck.Lock()
	defer b.wLck.Unlock()

	if resp.Data == nil {
		resp.Data = M{}
	}

	s, err := json.Marshal(resp)
	if err != nil {
		// if there is a token, it means the client is waiting for a response
		// so respond with the json error. cause of json encode failure includes: non-utf8 string
		if resp.Token == "" {
			return err
		}

		s, err = json.Marshal(M{
			"error": "margo broker: cannot encode json response: " + err.Error(),
		})
		if err != nil {
			return err
		}
	}

	// the only expected write failure are due to broken pipes
	// which usually means the client has gone away so just ignore the error
	b.w.Write(s)
	b.w.Write([]byte{'\n'})
	return nil
}

示例#4
文件: manifests.go 项目: CodeJuan/dockyard

func GetTagsListV2Handler(ctx *macaron.Context, log *logs.BeeLogger) (int, []byte) {
	namespace := ctx.Params(":namespace")
	repository := ctx.Params(":repository")

	r := new(models.Repository)
	if has, _, err := r.Has(namespace, repository); err != nil || has == false {
		log.Error("[REGISTRY API V2] Repository not found: %v", repository)

		result, _ := json.Marshal(map[string]string{"message": "Repository not found"})
		return http.StatusNotFound, result
	}

	data := map[string]interface{}{}
	tags := []string{}

	data["name"] = fmt.Sprintf("%s/%s", namespace, repository)

	for _, value := range r.Tags {
		t := new(models.Tag)
		if err := t.GetByKey(value); err != nil {
			log.Error("[REGISTRY API V2] Tag not found: %v", err.Error())

			result, _ := json.Marshal(map[string]string{"message": "Tag not found"})
			return http.StatusNotFound, result
		}

		tags = append(tags, t.Name)
	}

	data["tags"] = tags

	result, _ := json.Marshal(data)
	return http.StatusOK, result
}

示例#5
文件: server.go 项目: gechong/cockroach

// writeSummaries retrieves status summaries from the supplied
// NodeStatusRecorder and persists them to the cockroach data store.
func (s *Server) writeSummaries() error {
	nodeStatus, storeStatuses := s.recorder.GetStatusSummaries()
	if nodeStatus != nil {
		key := keys.NodeStatusKey(int32(nodeStatus.Desc.NodeID))
		if err := s.db.Put(key, nodeStatus); err != nil {
			return err
		}
		if log.V(1) {
			statusJSON, err := json.Marshal(nodeStatus)
			if err != nil {
				log.Errorf("error marshaling nodeStatus to json: %s", err)
			}
			log.Infof("node %d status: %s", nodeStatus.Desc.NodeID, statusJSON)
		}
	}

	for _, ss := range storeStatuses {
		key := keys.StoreStatusKey(int32(ss.Desc.StoreID))
		if err := s.db.Put(key, &ss); err != nil {
			return err
		}
		if log.V(1) {
			statusJSON, err := json.Marshal(&ss)
			if err != nil {
				log.Errorf("error marshaling storeStatus to json: %s", err)
			}
			log.Infof("store %d status: %s", ss.Desc.StoreID, statusJSON)
		}
	}
	return nil
}

示例#6
文件: config_test.go 项目: Psiphon-Labs/psiphon-tunnel-core

// Tests config file with JSON contents that don't match our structure
func (suite *ConfigTestSuite) Test_LoadConfig_GoodJson() {
	var testObj map[string]interface{}
	var testObjJSON []byte

	// TODO: Test that the config actually gets the values we expect?

	// Has all of our required fields, but no optional fields
	json.Unmarshal(suite.confStubBlob, &testObj)
	for i := range suite.nonRequiredFields {
		delete(testObj, suite.nonRequiredFields[i])
	}
	testObjJSON, _ = json.Marshal(testObj)
	_, err := LoadConfig(testObjJSON)
	suite.Nil(err, "JSON with good values for our required fields but no optional fields should succeed")

	// Has all of our required fields, and all optional fields
	_, err = LoadConfig(suite.confStubBlob)
	suite.Nil(err, "JSON with all good values for required and optional fields should succeed")

	// Has null for optional fields
	json.Unmarshal(suite.confStubBlob, &testObj)
	for i := range suite.nonRequiredFields {
		testObj[suite.nonRequiredFields[i]] = nil
	}
	testObjJSON, _ = json.Marshal(testObj)
	_, err = LoadConfig(testObjJSON)
	suite.Nil(err, "JSON with null for optional values should succeed")
}

示例#7
文件: build.go 项目: gwenlei/linux

func checkstatus(p *os.Process, pname string, timest string) bool {
	fmt.Println("checkstatus", pname, p)
	reportlog[timest]["status"] = pname + " running"
	reportlog[timest][pname+"start"] = time.Now().Format("20060102150405")
	liner, _ := json.Marshal(reportlog)
	ioutil.WriteFile("static/data/reportlog.json", liner, 0)
	pw, _ := p.Wait()
	fmt.Println("checkstatus over", p)
	fmt.Println("timest=", timest)
	reportlog[timest][pname+"stop"] = time.Now().Format("20060102150405")
	t1, _ := time.Parse("20060102150405", reportlog[timest][pname+"stop"])
	t2, _ := time.Parse("20060102150405", reportlog[timest][pname+"start"])
	reportlog[timest][pname+"time"] = strconv.Itoa(int(t1.Sub(t2)) / 1e9)
	fmt.Println("t1=", t1)
	fmt.Println("t2=", t2)
	fmt.Println("cost=", t1.Sub(t2))
	status := pw.Success()
	if status == true {
		reportlog[timest]["status"] = pname + " success"
		fmt.Println("checkstatus over success ", pname, p)
	} else {
		reportlog[timest]["status"] = pname + " failed"
		fmt.Println("checkstatus over failed ", pname, p)
	}
	liner, _ = json.Marshal(reportlog)
	ioutil.WriteFile("static/data/reportlog.json", liner, 0)
	return status

}

示例#8
文件: reserve_node_workflow.go 项目: cloudfoundry-incubator/bosh-rackhd-cpi-release

func generateReserveNodeWorkflow(uuid string) ([][]byte, []byte, error) {
	reserve := reserveNodeTask{}
	err := json.Unmarshal(reserveNodeTaskTemplate, &reserve)
	if err != nil {
		return nil, nil, fmt.Errorf("error unmarshalling reserve node task template: %s", err)
	}

	reserve.Name = fmt.Sprintf("%s.%s", reserve.Name, uuid)
	reserve.UnusedName = fmt.Sprintf("%s.%s", reserve.UnusedName, "UPLOADED_BY_RACKHD_CPI")

	reserveBytes, err := json.Marshal(reserve)
	if err != nil {
		return nil, nil, fmt.Errorf("error reserve provision node task template: %s", err)
	}

	w := reserveNodeWorkflow{}
	err = json.Unmarshal(reserveNodeWorkflowTemplate, &w)
	if err != nil {
		return nil, nil, fmt.Errorf("error unmarshalling reserve node workflow template: %s", err)
	}

	w.Name = fmt.Sprintf("%s.%s", w.Name, uuid)
	w.UnusedName = fmt.Sprintf("%s.%s", w.UnusedName, "UPLOADED_BY_RACKHD_CPI")
	w.Tasks[3].TaskName = fmt.Sprintf("%s.%s", w.Tasks[3].TaskName, uuid)

	wBytes, err := json.Marshal(w)
	if err != nil {
		return nil, nil, fmt.Errorf("error marshalling reserve node workflow template: %s", err)
	}

	return [][]byte{reserveBytes}, wBytes, nil
}

示例#9
文件: week.go 项目: kenshiro-o/recurrence

// Implement json.Marshaler interface.
func (self Week) MarshalJSON() ([]byte, error) {
	if int(self) == Last {
		return json.Marshal(map[string]interface{}{"week": "Last"})
	} else {
		return json.Marshal(map[string]interface{}{"week": int(self)})
	}
}

示例#10
文件: in_memory_registry_test.go 项目: charshy/registry

func TestIncomingReplication(t *testing.T) {
	if testing.Short() {
		t.Skip()
	}

	rep := createMockupReplication()
	close(rep.(*mockupReplication).syncChan) //Make sure no deadlock occur

	ns := auth.NamespaceFrom("ns1")

	r := newInMemoryRegistry(nil, rep)
	assert.NotContains(t, r.(*inMemoryRegistry).namespaces, ns)

	inst := newServiceInstance("Calc1", "192.168.0.1", 9080)
	payload, _ := json.Marshal(inst)
	data, _ := json.Marshal(&replicatedMsg{RepType: REGISTER, Payload: payload})
	rep.(*mockupReplication).NotifyChannel <- &replication.InMessage{cluster.MemberID("192.1.1.3:6100"), ns, data}

	catalog, err := r.GetCatalog(auth.NamespaceFrom("ns1"))

	// NOTICE, it may fail, since a race between the registry and the test...
	time.Sleep(time.Duration(5) * time.Second)

	assert.NoError(t, err)

	instances1, err1 := catalog.List("Calc1", protocolPredicate)
	assert.NoError(t, err1)
	assert.Len(t, instances1, 1)
}

示例#11
文件: otto_suite_test.go 项目: gitter-badger/gohan

func testJSONEquality(actual, expected interface{}) {
	actualJSON, err := json.Marshal(actual)
	Expect(err).ToNot(HaveOccurred())
	expectedJSON, err := json.Marshal(expected)
	Expect(err).ToNot(HaveOccurred())
	Expect(actualJSON).To(MatchJSON(expectedJSON))
}

示例#12
文件: main.go 项目: jigish/docker-simpleregistry

func (ctx *Context) generateAncestry(imageId string, parentId string) error {
	if parentId == "" {
		selfAncestryJson, err := json.Marshal([]string{imageId})
		if err != nil {
			return err
		}
		if err := ctx.storage.PutContent(storage.ImageAncestryPath(imageId), selfAncestryJson); err != nil {
			return err
		}
		return nil
	}

	data, err := ctx.storage.GetContent(storage.ImageAncestryPath(parentId))
	if err != nil {
		return err
	}

	var ancestry []string
	if err := json.Unmarshal(data, &ancestry); err != nil {
		return err
	}

	newAncestry := []string{imageId}
	newAncestry = append(newAncestry, ancestry...)

	data, err = json.Marshal(newAncestry)
	if err != nil {
		return err
	}

	ctx.storage.PutContent(storage.ImageAncestryPath(imageId), data)

	return nil
}

示例#13
文件: topicpatchcompiler.go 项目: InteractiveLecture/lecture-service

//database checked
func generateAddModule(id, userId, jwt string, officers, assistants map[string]bool, op *jsonpatch.Operation, params map[string]string) (*jsonpatch.CommandContainer, error) {
	if err := checkAuthorityAndValidatePatch(jsonpatch.ADD, op.Type, userId, officers); err != nil {
		log.Println("Patch not acceptable: ", err)
		return nil, err
	}
	value := op.Value.(map[string]interface{})
	command := buildDefaultCommand("SELECT add_module(%v)", value["id"].(string), id, value["description"].(string), value["video_id"].(string), value["script_id"].(string), value["parents"])
	command.AfterCallback = func(transaction, prev interface{}) (interface{}, error) {
		client := serviceclient.New("acl-service")
		entity := map[string]interface{}{
			"id":     value["id"].(string),
			"parent": id,
		}
		jsonEntity, _ := json.Marshal(entity)
		err := checkStatus(client.Post("/objects", "json", bytes.NewReader(jsonEntity), "Authorization", jwt))
		if err != nil {
			log.Println("error while creating acl entry: ", err)
			return nil, err
		}
		if len(assistants) > 0 {
			assistantsString := ""
			for k, _ := range assistants {
				assistantsString = assistantsString + "&sid=" + k
			}
			assistantsString = strings.TrimLeft(assistantsString, "&")
			permissions, _ := json.Marshal(map[string]bool{"read_permission": true, "create_permission": true, "update_permission": false, "delete_permission": false})
			return nil, checkStatus(client.Put(fmt.Sprintf("/objects/%s/permissions?%s", value["id"], assistantsString), "application/json", bytes.NewReader(permissions), "Authorization", jwt))
		}
		return nil, nil
	}
	return command, nil
}

示例#14
文件: timestamp_test.go 项目: moxiegirl/notary

func TestGetTimestampNewSnapshot(t *testing.T) {
	store := storage.NewMemStorage()
	crypto := signed.NewEd25519()

	snapshot := &data.SignedSnapshot{
		Signed: data.Snapshot{
			Expires: data.DefaultExpires(data.CanonicalSnapshotRole),
		},
	}
	snapshot.Signed.Version = 0
	snapJSON, _ := json.Marshal(snapshot)

	store.UpdateCurrent("gun", storage.MetaUpdate{Role: "snapshot", Version: 0, Data: snapJSON})
	// create a key to be used by GetTimestamp
	_, err := GetOrCreateTimestampKey("gun", store, crypto, data.ED25519Key)
	assert.Nil(t, err, "GetKey errored")

	ts1, err := GetOrCreateTimestamp("gun", store, crypto)
	assert.Nil(t, err, "GetTimestamp errored")

	snapshot = &data.SignedSnapshot{
		Signed: data.Snapshot{
			Expires: data.DefaultExpires(data.CanonicalSnapshotRole),
		},
	}
	snapshot.Signed.Version = 1
	snapJSON, _ = json.Marshal(snapshot)

	store.UpdateCurrent("gun", storage.MetaUpdate{Role: "snapshot", Version: 1, Data: snapJSON})

	ts2, err := GetOrCreateTimestamp("gun", store, crypto)
	assert.NoError(t, err, "GetTimestamp errored")

	assert.NotEqual(t, ts1, ts2, "Timestamp was not regenerated when snapshot changed")
}

示例#15
文件: droplets.go 项目: Originate/terraform

// MarshalJSON returns either the slug or id of the image. It returns the id
// if the slug is empty.
func (d DropletCreateImage) MarshalJSON() ([]byte, error) {
	if d.Slug != "" {
		return json.Marshal(d.Slug)
	}

	return json.Marshal(d.ID)
}

示例#16
文件: protocol.go 项目: pombredanne/gomrjob

// a json Key, and a json value
func JsonInternalOutputProtocol(writer io.Writer) (*sync.WaitGroup, chan<- KeyValue) {
	w := bufio.NewWriter(writer)
	in := make(chan KeyValue, 100)
	tab := []byte("\t")
	newline := []byte("\n")
	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		for kv := range in {
			kBytes, err := json.Marshal(kv.Key)
			if err != nil {
				Counter("JsonInternalOutputProtocol", "unable to json encode key", 1)
				log.Printf("%s - failed encoding %v", err, kv.Key)
				continue
			}
			vBytes, err := json.Marshal(kv.Value)
			if err != nil {
				Counter("JsonInternalOutputProtocol", "unable to json encode value", 1)
				log.Printf("%s - failed encoding %v", err, kv.Value)
				continue
			}
			w.Write(kBytes)
			w.Write(tab)
			w.Write(vBytes)
			w.Write(newline)
		}
		w.Flush()
		wg.Done()
	}()
	return &wg, in
}

示例#17
文件: droplets.go 项目: Originate/terraform

// MarshalJSON returns either the fingerprint or id of the ssh key. It returns
// the id if the fingerprint is empty.
func (d DropletCreateSSHKey) MarshalJSON() ([]byte, error) {
	if d.Fingerprint != "" {
		return json.Marshal(d.Fingerprint)
	}

	return json.Marshal(d.ID)
}

示例#18
文件: cniserver.go 项目: jojimt/netplugin

// Simple Wrapper for http handlers
func makeHTTPHandler(handlerFunc restAPIFunc) http.HandlerFunc {
	// Create a closure and return an anonymous function
	return func(w http.ResponseWriter, r *http.Request) {
		// Call the handler
		resp, err := handlerFunc(r)
		if err != nil {
			// Log error
			log.Errorf("Handler for %s %s returned error: %s", r.Method, r.URL, err)

			if resp == nil {
				// Send HTTP response
				http.Error(w, err.Error(), http.StatusInternalServerError)
			} else {
				// Send HTTP response as Json
				content, err1 := json.Marshal(resp)
				if err1 != nil {
					http.Error(w, err.Error(), http.StatusInternalServerError)
					return
				}

				w.WriteHeader(http.StatusInternalServerError)
				w.Write(content)
			}
		} else {
			// Send HTTP response as Json
			content, err := json.Marshal(resp)
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			w.Write(content)
		}
	}
}

示例#19
文件: util_test.go 项目: mweagle/Sparta

/*
   "Fn::GetAtt" : []string{"ResName","AttrName"},
*/
func TestExpand(t *testing.T) {

	for _, eachTest := range userdataPassingTests {
		testReader := strings.NewReader(eachTest.input)
		expandResult, expandResultErr := ConvertToTemplateExpression(testReader, conversionParams)
		if nil != expandResultErr {
			t.Errorf("%s (Input: %s)", expandResultErr, eachTest.input)
		} else {
			testOutput := map[string]interface{}{
				"Fn::Join": []interface{}{
					"",
					eachTest.output,
				},
			}
			expectedResult, expectedResultErr := json.Marshal(testOutput)
			if nil != expectedResultErr {
				t.Error(expectedResultErr)
			} else {
				actualMarshal, actualMarshalErr := json.Marshal(expandResult)
				if nil != actualMarshalErr {
					t.Errorf("%s (Input: %s)", actualMarshalErr, eachTest.input)
				} else if string(expectedResult) != string(actualMarshal) {
					t.Errorf("Failed to validate\n")
					t.Errorf("\tEXPECTED: %s\n", string(expectedResult))
					t.Errorf("\tACTUAL: %s\n", string(actualMarshal))
				} else {
					t.Logf("Validated: %s == %s", string(expectedResult), string(actualMarshal))
				}
			}
		}
	}
}

示例#20
文件: schema.go 项目: yourchanges/go-swagger

// MarshalJSON marshal this to JSON
func (s Schema) MarshalJSON() ([]byte, error) {
	b1, err := json.Marshal(s.schemaProps)
	if err != nil {
		return nil, fmt.Errorf("schema props %v", err)
	}
	b2, err := json.Marshal(s.vendorExtensible)
	if err != nil {
		return nil, fmt.Errorf("vendor props %v", err)
	}
	b3, err := s.Ref.MarshalJSON()
	if err != nil {
		return nil, fmt.Errorf("ref prop %v", err)
	}
	b4, err := s.Schema.MarshalJSON()
	if err != nil {
		return nil, fmt.Errorf("schema prop %v", err)
	}
	b5, err := json.Marshal(s.swaggerSchemaProps)
	if err != nil {
		return nil, fmt.Errorf("common validations %v", err)
	}
	var b6 []byte
	if s.ExtraProps != nil {
		jj, err := json.Marshal(s.ExtraProps)
		if err != nil {
			return nil, fmt.Errorf("extra props %v", err)
		}
		b6 = jj
	}
	return swag.ConcatJSON(b1, b2, b3, b4, b5, b6), nil
}

示例#21
文件: manifests.go 项目: CodeJuan/dockyard

func GetManifestsV2Handler(ctx *macaron.Context, log *logs.BeeLogger) (int, []byte) {
	t := new(models.Tag)

	namespace := ctx.Params(":namespace")
	repository := ctx.Params(":repository")
	if err := t.Get(namespace, repository, ctx.Params(":tag")); err != nil {
		log.Error("[REGISTRY API V2] Manifest not found: %v", err.Error())

		result, _ := json.Marshal(map[string]string{"message": "Manifest not found"})
		return http.StatusNotFound, result
	}

	digest, err := utils.DigestManifest([]byte(t.Manifest))
	if err != nil {
		log.Error("[REGISTRY API V2] Get manifest digest failed: %v", err.Error())

		result, _ := json.Marshal(map[string]string{"message": "Get manifest digest failed"})
		return http.StatusBadRequest, result
	}

	ctx.Resp.Header().Set("Content-Type", "application/json; charset=utf-8")
	ctx.Resp.Header().Set("Docker-Content-Digest", digest)
	ctx.Resp.Header().Set("Content-Length", fmt.Sprint(len(t.Manifest)))

	return http.StatusOK, []byte(t.Manifest)
}

示例#22
文件: stats_test.go 项目: BenLubar/cbgb

func TestAggStatsSampleJSON(t *testing.T) {
	a := NewAggStats(func() Aggregatable {
		return &BucketStats{}
	})
	if a == nil {
		t.Errorf("Expected NewAggStats() to work")
	}

	s := &BucketStats{Ops: 10}
	for i := 0; i < 5; i++ {
		a.AddSample(s)
	}

	j0, err := json.Marshal(a.Levels[0])
	if err != nil {
		t.Errorf("Expected json marshal to work, got: %v", err)
	}

	ja, err := json.Marshal(a)
	if err != nil {
		t.Errorf("Expected json marshal to work, got: %v", err)
	}
	if bytes.Index(ja, j0) <= 0 {
		t.Errorf("Expected json to be in the larger json, got: %v versus %v",
			j0, ja)
	}
}

示例#23
文件: chainsvrresults.go 项目: jimmysong/btcd

// MarshalJSON provides a custom Marshal method for Vin.
func (v *Vin) MarshalJSON() ([]byte, error) {
	if v.IsCoinBase() {
		coinbaseStruct := struct {
			Coinbase string `json:"coinbase"`
			Sequence uint32 `json:"sequence"`
		}{
			Coinbase: v.Coinbase,
			Sequence: v.Sequence,
		}
		return json.Marshal(coinbaseStruct)
	}

	txStruct := struct {
		Txid      string     `json:"txid"`
		Vout      uint32     `json:"vout"`
		ScriptSig *ScriptSig `json:"scriptSig"`
		Sequence  uint32     `json:"sequence"`
	}{
		Txid:      v.Txid,
		Vout:      v.Vout,
		ScriptSig: v.ScriptSig,
		Sequence:  v.Sequence,
	}
	return json.Marshal(txStruct)
}

示例#24
文件: time.go 项目: c2h5oh/norm

// MarshalJSON Marshal just the value of String
func (nt NullTime) MarshalJSON() ([]byte, error) {
	if nt.Valid {
		return json.Marshal(nt.Time)
	}
	return json.Marshal(nil)

}

示例#25
文件: apply_test.go 项目: XbinZh/kubernetes

func annotateRuntimeObject(t *testing.T, originalObj, currentObj runtime.Object, kind string) (string, []byte) {
	originalAccessor, err := meta.Accessor(originalObj)
	if err != nil {
		t.Fatal(err)
	}

	originalLabels := originalAccessor.GetLabels()
	originalLabels["DELETE_ME"] = "DELETE_ME"
	originalAccessor.SetLabels(originalLabels)
	original, err := json.Marshal(originalObj)
	if err != nil {
		t.Fatal(err)
	}

	currentAccessor, err := meta.Accessor(currentObj)
	if err != nil {
		t.Fatal(err)
	}

	currentAnnotations := currentAccessor.GetAnnotations()
	if currentAnnotations == nil {
		currentAnnotations = make(map[string]string)
	}
	currentAnnotations[annotations.LastAppliedConfigAnnotation] = string(original)
	currentAccessor.SetAnnotations(currentAnnotations)
	current, err := json.Marshal(currentObj)
	if err != nil {
		t.Fatal(err)
	}

	return currentAccessor.GetName(), current
}

示例#26
文件: queryhandlers.go 项目: sboyettedh/whiplash

// qhEcho is an example query handler. It simply creates an
// appropriate response and returns it.
func qhEcho(args [][]byte) ([]byte, error) {
	// we have to have a subcommand!
	if len(args) == 0 {
		return qhErrNoSubCmd("echo")
	}
	// gin up a blank success reponse
	resp := qhStubResponse("echo", args)
	// the Data field of a QueryResponse contains the result of the
	// handler's processing. it is also of type json.RawMessage, which
	// means that it's a byteslice of pre-marshalled data. here, we
	// catenate together the non-subcmd args and use that.
	respstr := ""
	for _, x := range resp.Args {
		respstr = respstr + string(x) + " "
	}
	// marshal the string we built, and make it resp.Data if there's
	// no problem.
	data, err := json.Marshal(respstr)
	if err != nil {
		log.Println("echoQHandler: ", err)
		return nil, err
	}
	resp.Data = data
	// json.Marshal returns ([]byte, error) which satisfies our
	// signature, so just return that!
	return json.Marshal(resp)
}

示例#27
文件: encode_test.go 项目: nolenroyalty/bangarang

// Issue 5245.
func TestEmbeddedBug(t *testing.T) {
	v := BugB{
		BugA{"A"},
		"B",
	}
	b, err := json.Marshal(v)
	if err != nil {
		t.Fatal("Marshal:", err)
	}
	want := `{"S":"B"}`
	got := string(b)
	if got != want {
		t.Fatalf("Marshal: got %s want %s", got, want)
	}
	// Now check that the duplicate field, S, does not appear.
	x := BugX{
		A: 23,
	}
	b, err = json.Marshal(x)
	if err != nil {
		t.Fatal("Marshal:", err)
	}
	want = `{"A":23}`
	got = string(b)
	if got != want {
		t.Fatalf("Marshal: got %s want %s", got, want)
	}
}

示例#28
文件: client.go 项目: vivienschilis/pusher-http-go

func (c *Client) authenticateChannel(params []byte, member *MemberData) (response []byte, err error) {
	channelName, socketId, err := parseAuthRequestParams(params)

	if err != nil {
		return
	}

	if err = validateSocketId(&socketId); err != nil {
		return
	}

	stringToSign := strings.Join([]string{socketId, channelName}, ":")

	var jsonUserData string

	if member != nil {
		var _jsonUserData []byte
		_jsonUserData, err = json.Marshal(member)
		if err != nil {
			return
		}

		jsonUserData = string(_jsonUserData)
		stringToSign = strings.Join([]string{stringToSign, jsonUserData}, ":")
	}

	_response := createAuthMap(c.Key, c.Secret, stringToSign)

	if member != nil {
		_response["channel_data"] = jsonUserData
	}

	response, err = json.Marshal(_response)
	return
}

示例#29
文件: dynamizer_test.go 项目: docker/goamz

// What we're trying to do here is compare the JSON encoded values, but we can't
// to a simple encode + string compare since JSON encoding is not ordered. So
// what we do is JSON encode, then JSON decode into untyped maps, and then
// finally do a recursive comparison.
func compareObjects(t *testing.T, expected interface{}, actual interface{}) {
	expectedBytes, err := json.Marshal(expected)
	if err != nil {
		t.Fatal(err)
		return
	}
	actualBytes, err := json.Marshal(actual)
	if err != nil {
		t.Fatal(err)
		return
	}
	var expectedUntyped, actualUntyped map[string]interface{}
	err = json.Unmarshal(expectedBytes, &expectedUntyped)
	if err != nil {
		t.Fatal(err)
		return
	}
	err = json.Unmarshal(actualBytes, &actualUntyped)
	if err != nil {
		t.Fatal(err)
		return
	}
	if !reflect.DeepEqual(expectedUntyped, actualUntyped) {
		t.Fatalf("Expected %s, got %s", string(expectedBytes), string(actualBytes))
	}
}

示例#30
文件: node.go 项目: kubernetes/kubernetes

// PatchNodeStatus patches node status.
func PatchNodeStatus(c clientset.Interface, nodeName types.NodeName, oldNode *v1.Node, newNode *v1.Node) (*v1.Node, error) {
	oldData, err := json.Marshal(oldNode)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal old node %#v for node %q: %v", oldNode, nodeName, err)
	}

	// Reset spec to make sure only patch for Status or ObjectMeta is generated.
	// Note that we don't reset ObjectMeta here, because:
	// 1. This aligns with Nodes().UpdateStatus().
	// 2. Some component does use this to update node annotations.
	newNode.Spec = oldNode.Spec
	newData, err := json.Marshal(newNode)
	if err != nil {
		return nil, fmt.Errorf("failed to marshal new node %#v for node %q: %v", newNode, nodeName, err)
	}

	patchBytes, err := strategicpatch.CreateTwoWayMergePatch(oldData, newData, v1.Node{})
	if err != nil {
		return nil, fmt.Errorf("failed to create patch for node %q: %v", nodeName, err)
	}

	updatedNode, err := c.Core().Nodes().Patch(string(nodeName), types.StrategicMergePatchType, patchBytes, "status")
	if err != nil {
		return nil, fmt.Errorf("failed to patch status %q for node %q: %v", patchBytes, nodeName, err)
	}
	return updatedNode, nil
}

展开阅读全文