• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang api.Encode函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/GoogleCloudPlatform/kubernetes/pkg/api.Encode函数的典型用法代码示例。如果您正苦于以下问题:Golang Encode函数的具体用法?Golang Encode怎么用?Golang Encode使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Encode函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: TestDoRequestNewWayObj

func TestDoRequestNewWayObj(t *testing.T) {
	reqObj := &api.Pod{JSONBase: api.JSONBase{ID: "foo"}}
	reqBodyExpected, _ := api.Encode(reqObj)
	expectedObj := &api.Service{Port: 12345}
	expectedBody, _ := api.Encode(expectedObj)
	fakeHandler := util.FakeHandler{
		StatusCode:   200,
		ResponseBody: string(expectedBody),
		T:            t,
	}
	testServer := httptest.NewServer(&fakeHandler)
	auth := AuthInfo{User: "user", Password: "pass"}
	c := NewOrDie(testServer.URL, &auth)
	obj, err := c.Verb("POST").
		Path("foo/bar").
		Path("baz").
		SelectorParam("labels", labels.Set{"name": "foo"}.AsSelector()).
		Timeout(time.Second).
		Body(reqObj).
		Do().Get()
	if err != nil {
		t.Errorf("Unexpected error: %v %#v", err, err)
		return
	}
	if obj == nil {
		t.Error("nil obj")
	} else if !reflect.DeepEqual(obj, expectedObj) {
		t.Errorf("Expected: %#v, got %#v", expectedObj, obj)
	}
	tmpStr := string(reqBodyExpected)
	fakeHandler.ValidateRequest(t, "/api/v1beta1/foo/bar/baz?labels=name%3Dfoo", "POST", &tmpStr)
	if fakeHandler.RequestReceived.Header["Authorization"] == nil {
		t.Errorf("Request is missing authorization header: %#v", *fakeHandler.RequestReceived)
	}
}
开发者ID:jhuamonte,项目名称:kubernetes,代码行数:35,代码来源:request_test.go


示例2: TestAtomicUpdate

func TestAtomicUpdate(t *testing.T) {
	fakeClient := MakeFakeEtcdClient(t)
	fakeClient.TestIndex = true
	helper := EtcdHelper{fakeClient}

	// Create a new node.
	fakeClient.ExpectNotFoundGet("/some/key")
	obj := TestResource{JSONBase: api.JSONBase{ID: "foo"}, Value: 1}
	err := helper.AtomicUpdate("/some/key", &TestResource{}, func(in interface{}) (interface{}, error) {
		return obj, nil
	})
	if err != nil {
		t.Errorf("Unexpected error %#v", err)
	}
	data, err := api.Encode(obj)
	if err != nil {
		t.Errorf("Unexpected error %#v", err)
	}
	expect := string(data)
	got := fakeClient.Data["/some/key"].R.Node.Value
	if expect != got {
		t.Errorf("Wanted %v, got %v", expect, got)
	}
	return

	// Update an existing node.
	callbackCalled := false
	objUpdate := &TestResource{JSONBase: api.JSONBase{ID: "foo"}, Value: 2}
	err = helper.AtomicUpdate("/some/key", &TestResource{}, func(in interface{}) (interface{}, error) {
		callbackCalled = true

		if in.(*TestResource).Value != 1 {
			t.Errorf("Callback input was not current set value")
		}

		return objUpdate, nil
	})
	if err != nil {
		t.Errorf("Unexpected error %#v", err)
	}
	data, err = api.Encode(objUpdate)
	if err != nil {
		t.Errorf("Unexpected error %#v", err)
	}
	expect = string(data)
	got = fakeClient.Data["/some/key"].R.Node.Value
	if expect != got {
		t.Errorf("Wanted %v, got %v", expect, got)
	}

	if !callbackCalled {
		t.Errorf("tryUpdate callback should have been called.")
	}
}
开发者ID:htomika,项目名称:kubernetes,代码行数:54,代码来源:etcd_tools_test.go


示例3: TestDoRequestNewWayFile

func TestDoRequestNewWayFile(t *testing.T) {
	reqObj := &api.Pod{JSONBase: api.JSONBase{ID: "foo"}}
	reqBodyExpected, err := api.Encode(reqObj)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	file, err := ioutil.TempFile("", "foo")
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	_, err = file.Write(reqBodyExpected)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	expectedObj := &api.Service{Port: 12345}
	expectedBody, _ := api.Encode(expectedObj)
	fakeHandler := util.FakeHandler{
		StatusCode:   200,
		ResponseBody: string(expectedBody),
		T:            t,
	}
	testServer := httptest.NewServer(&fakeHandler)
	auth := AuthInfo{User: "user", Password: "pass"}
	s := New(testServer.URL, &auth)
	obj, err := s.Verb("POST").
		Path("foo/bar").
		Path("baz").
		ParseSelector("name=foo").
		Timeout(time.Second).
		Body(file.Name()).
		Do().Get()
	if err != nil {
		t.Errorf("Unexpected error: %v %#v", err, err)
		return
	}
	if obj == nil {
		t.Error("nil obj")
	} else if !reflect.DeepEqual(obj, expectedObj) {
		t.Errorf("Expected: %#v, got %#v", expectedObj, obj)
	}
	tmpStr := string(reqBodyExpected)
	fakeHandler.ValidateRequest(t, "/api/v1beta1/foo/bar/baz", "POST", &tmpStr)
	if fakeHandler.RequestReceived.URL.RawQuery != "labels=name%3Dfoo" {
		t.Errorf("Unexpected query: %v", fakeHandler.RequestReceived.URL.RawQuery)
	}
	if fakeHandler.RequestReceived.Header["Authorization"] == nil {
		t.Errorf("Request is missing authorization header: %#v", *fakeHandler.RequestReceived)
	}
}
开发者ID:nyaxt,项目名称:kubernetes,代码行数:52,代码来源:request_test.go


示例4: TestDoRequestAcceptedSuccess

func TestDoRequestAcceptedSuccess(t *testing.T) {
	status := api.Status{Status: api.StatusSuccess}
	expectedBody, _ := api.Encode(status)
	fakeHandler := util.FakeHandler{
		StatusCode:   202,
		ResponseBody: string(expectedBody),
		T:            t,
	}
	testServer := httptest.NewTLSServer(&fakeHandler)
	request, _ := http.NewRequest("GET", testServer.URL+"/foo/bar", nil)
	auth := AuthInfo{User: "user", Password: "pass"}
	c := New(testServer.URL, &auth)
	body, err := c.doRequest(request)
	if request.Header["Authorization"] == nil {
		t.Errorf("Request is missing authorization header: %#v", *request)
	}
	if err != nil {
		t.Errorf("Unexpected error %#v", err)
	}
	statusOut, err := api.Decode(body)
	if err != nil {
		t.Errorf("Unexpected error %#v", err)
	}
	if !reflect.DeepEqual(&status, statusOut) {
		t.Errorf("Unexpected mis-match. Expected %#v.  Saw %#v", status, statusOut)
	}
	fakeHandler.ValidateRequest(t, "/foo/bar", "GET", nil)
}
开发者ID:jamesblunt,项目名称:kubernetes,代码行数:28,代码来源:client_test.go


示例5: TestHandleWatchResponseDelete

func TestHandleWatchResponseDelete(t *testing.T) {
	body, _ := api.Encode(makePodList(2))
	fakeHandler := util.FakeHandler{
		StatusCode:   200,
		ResponseBody: string(body),
	}
	testServer := httptest.NewTLSServer(&fakeHandler)
	client := client.New(testServer.URL, nil)

	fakePodControl := FakePodControl{}

	manager := MakeReplicationManager(nil, client)
	manager.podControl = &fakePodControl

	controller := makeReplicationController(2)

	// TODO: fixme when etcd writing uses api.Encode
	data, err := json.Marshal(controller)
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}
	controllerOut, err := manager.handleWatchResponse(&etcd.Response{
		Action: "delete",
		PrevNode: &etcd.Node{
			Value: string(data),
		},
	})
	if err != nil {
		t.Errorf("Unexpected error: %#v", err)
	}
	if !reflect.DeepEqual(controller, *controllerOut) {
		t.Errorf("Unexpected mismatch.  Expected %#v, Saw: %#v", controller, controllerOut)
	}
}
开发者ID:RubanDeventhiran,项目名称:kubernetes,代码行数:34,代码来源:replication_controller_test.go


示例6: PrintObj

// PrintObj is an implementation of ResourcePrinter.PrintObj which simply writes the object to the Writer.
func (i *IdentityPrinter) PrintObj(obj interface{}, output io.Writer) error {
	data, err := api.Encode(obj)
	if err != nil {
		return err
	}
	return i.Print(data, output)
}
开发者ID:289,项目名称:kubernetes,代码行数:8,代码来源:resource_printer.go


示例7: TestReadme

func TestReadme(t *testing.T) {
	path := "../README.md"
	data, err := ioutil.ReadFile(path)
	if err != nil {
		t.Fatalf("Unable to read file: %v", err)
	}

	match := jsonRegexp.FindStringSubmatch(string(data))
	if match == nil {
		return
	}
	for _, json := range match[1:] {
		expectedType := &api.Pod{}
		if err := api.DecodeInto([]byte(json), expectedType); err != nil {
			t.Errorf("%s did not decode correctly: %v\n%s", path, err, string(data))
			return
		}
		if errors := validateObject(expectedType); len(errors) > 0 {
			t.Errorf("%s did not validate correctly: %v", path, errors)
		}
		encoded, err := api.Encode(expectedType)
		if err != nil {
			t.Errorf("Could not encode object: %v", err)
			continue
		}
		t.Logf("Found pod %s\n%s", json, encoded)
	}
}
开发者ID:nvdnkpr,项目名称:kubernetes,代码行数:28,代码来源:examples_test.go


示例8: TestWatchInterpretation_ListDelete

func TestWatchInterpretation_ListDelete(t *testing.T) {
	called := false
	w := newEtcdWatcher(true, func(interface{}) bool {
		called = true
		return true
	})
	pod := &api.Pod{JSONBase: api.JSONBase{ID: "foo"}}
	podBytes, _ := api.Encode(pod)

	go w.sendResult(&etcd.Response{
		Action: "delete",
		PrevNode: &etcd.Node{
			Nodes: etcd.Nodes{
				{
					Value: string(podBytes),
				},
			},
		},
	})

	got := <-w.outgoing
	if e, a := watch.Deleted, got.Type; e != a {
		t.Errorf("Expected %v, got %v", e, a)
	}
	if e, a := pod, got.Object; !reflect.DeepEqual(e, a) {
		t.Errorf("Expected %v, got %v", e, a)
	}
	if !called {
		t.Errorf("filter never called")
	}
}
开发者ID:jamesblunt,项目名称:kubernetes,代码行数:31,代码来源:etcd_tools_test.go


示例9: TestDoRequestAccepted

func TestDoRequestAccepted(t *testing.T) {
	status := api.Status{Status: api.StatusWorking}
	expectedBody, _ := api.Encode(status)
	fakeHandler := util.FakeHandler{
		StatusCode:   202,
		ResponseBody: string(expectedBody),
		T:            t,
	}
	testServer := httptest.NewTLSServer(&fakeHandler)
	request, _ := http.NewRequest("GET", testServer.URL+"/foo/bar", nil)
	auth := AuthInfo{User: "user", Password: "pass"}
	c := New(testServer.URL, &auth)
	body, err := c.doRequest(request)
	if request.Header["Authorization"] == nil {
		t.Errorf("Request is missing authorization header: %#v", *request)
	}
	if err == nil {
		t.Error("Unexpected non-error")
		return
	}
	se, ok := err.(*StatusErr)
	if !ok {
		t.Errorf("Unexpected kind of error: %#v", err)
		return
	}
	if !reflect.DeepEqual(se.Status, status) {
		t.Errorf("Unexpected status: %#v", se.Status)
	}
	if body != nil {
		t.Errorf("Expected nil body, but saw: '%s'", body)
	}
	fakeHandler.ValidateRequest(t, "/foo/bar", "GET", nil)
}
开发者ID:jamesblunt,项目名称:kubernetes,代码行数:33,代码来源:client_test.go


示例10: TestCreate

func TestCreate(t *testing.T) {
	simpleStorage := &SimpleRESTStorage{}
	handler := New(map[string]RESTStorage{
		"foo": simpleStorage,
	}, "/prefix/version")
	handler.asyncOpWait = 0
	server := httptest.NewServer(handler)
	client := http.Client{}

	simple := Simple{
		Name: "foo",
	}
	data, _ := api.Encode(simple)
	request, err := http.NewRequest("POST", server.URL+"/prefix/version/foo", bytes.NewBuffer(data))
	expectNoError(t, err)
	response, err := client.Do(request)
	expectNoError(t, err)
	if response.StatusCode != http.StatusAccepted {
		t.Errorf("Unexpected response %#v", response)
	}

	var itemOut api.Status
	body, err := extractBody(response, &itemOut)
	expectNoError(t, err)
	if itemOut.Status != api.StatusWorking || itemOut.Details == "" {
		t.Errorf("Unexpected status: %#v (%s)", itemOut, string(body))
	}
}
开发者ID:jamesblunt,项目名称:kubernetes,代码行数:28,代码来源:apiserver_test.go


示例11: Body

// Body makes the request use obj as the body. Optional.
// If obj is a string, try to read a file of that name.
// If obj is a []byte, send it directly.
// Otherwise, assume obj is an api type and marshall it correctly.
func (r *Request) Body(obj interface{}) *Request {
	if r.err != nil {
		return r
	}
	switch t := obj.(type) {
	case string:
		data, err := ioutil.ReadFile(t)
		if err != nil {
			r.err = err
			return r
		}
		r.body = bytes.NewBuffer(data)
	case []byte:
		r.body = bytes.NewBuffer(t)
	case io.Reader:
		r.body = obj.(io.Reader)
	default:
		data, err := api.Encode(obj)
		if err != nil {
			r.err = err
			return r
		}
		r.body = bytes.NewBuffer(data)
	}
	return r
}
开发者ID:289,项目名称:kubernetes,代码行数:30,代码来源:request.go


示例12: TestCreateNotFound

func TestCreateNotFound(t *testing.T) {
	handler := New(map[string]RESTStorage{
		"simple": &SimpleRESTStorage{
			// storage.Create can fail with not found error in theory.
			// See https://github.com/GoogleCloudPlatform/kubernetes/pull/486#discussion_r15037092.
			errors: map[string]error{"create": NewNotFoundErr("simple", "id")},
		},
	}, "/prefix/version")
	server := httptest.NewServer(handler)
	client := http.Client{}

	simple := Simple{Name: "foo"}
	data, _ := api.Encode(simple)
	request, err := http.NewRequest("POST", server.URL+"/prefix/version/simple", bytes.NewBuffer(data))
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	response, err := client.Do(request)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if response.StatusCode != http.StatusNotFound {
		t.Errorf("Unexpected response %#v", response)
	}
}
开发者ID:Barba-studio,项目名称:kubernetes,代码行数:27,代码来源:apiserver_test.go


示例13: TestUpdateMissing

func TestUpdateMissing(t *testing.T) {
	storage := map[string]RESTStorage{}
	ID := "id"
	simpleStorage := SimpleRESTStorage{
		errors: map[string]error{"update": NewNotFoundErr("simple", ID)},
	}
	storage["simple"] = &simpleStorage
	handler := New(storage, "/prefix/version")
	server := httptest.NewServer(handler)

	item := Simple{
		Name: "bar",
	}
	body, err := api.Encode(item)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	client := http.Client{}
	request, err := http.NewRequest("PUT", server.URL+"/prefix/version/simple/"+ID, bytes.NewReader(body))
	response, err := client.Do(request)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if response.StatusCode != http.StatusNotFound {
		t.Errorf("Unexpected response %#v", response)
	}
}
开发者ID:Barba-studio,项目名称:kubernetes,代码行数:29,代码来源:apiserver_test.go


示例14: TestUpdate

func TestUpdate(t *testing.T) {
	storage := map[string]RESTStorage{}
	simpleStorage := SimpleRESTStorage{}
	ID := "id"
	storage["simple"] = &simpleStorage
	handler := New(storage, "/prefix/version")
	server := httptest.NewServer(handler)

	item := Simple{
		Name: "bar",
	}
	body, err := api.Encode(item)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	client := http.Client{}
	request, err := http.NewRequest("PUT", server.URL+"/prefix/version/simple/"+ID, bytes.NewReader(body))
	_, err = client.Do(request)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if simpleStorage.updated.Name != item.Name {
		t.Errorf("Unexpected update value %#v, expected %#v.", simpleStorage.updated, item)
	}
}
开发者ID:Barba-studio,项目名称:kubernetes,代码行数:27,代码来源:apiserver_test.go


示例15: TestPolling

func TestPolling(t *testing.T) {
	objects := []interface{}{
		&api.Status{Status: api.StatusWorking, Details: "1234"},
		&api.Status{Status: api.StatusWorking, Details: "1234"},
		&api.Status{Status: api.StatusWorking, Details: "1234"},
		&api.Status{Status: api.StatusWorking, Details: "1234"},
		&api.Status{Status: api.StatusSuccess},
	}

	callNumber := 0
	testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		data, err := api.Encode(objects[callNumber])
		if err != nil {
			t.Errorf("Unexpected encode error")
		}
		callNumber++
		w.Write(data)
	}))

	auth := AuthInfo{User: "user", Password: "pass"}
	s := New(testServer.URL, &auth)

	trials := []func(){
		func() {
			// Check that we do indeed poll when asked to.
			obj, err := s.Get().PollPeriod(5 * time.Millisecond).Do().Get()
			if err != nil {
				t.Errorf("Unexpected error: %v %#v", err, err)
				return
			}
			if s, ok := obj.(*api.Status); !ok || s.Status != api.StatusSuccess {
				t.Errorf("Unexpected return object: %#v", obj)
				return
			}
			if callNumber != len(objects) {
				t.Errorf("Unexpected number of calls: %v", callNumber)
			}
		},
		func() {
			// Check that we don't poll when asked not to.
			obj, err := s.Get().PollPeriod(0).Do().Get()
			if err == nil {
				t.Errorf("Unexpected non error: %v", obj)
				return
			}
			if se, ok := err.(*StatusErr); !ok || se.Status.Status != api.StatusWorking {
				t.Errorf("Unexpected kind of error: %#v", err)
				return
			}
			if callNumber != 1 {
				t.Errorf("Unexpected number of calls: %v", callNumber)
			}
		},
	}
	for _, f := range trials {
		callNumber = 0
		f()
	}
}
开发者ID:nyaxt,项目名称:kubernetes,代码行数:59,代码来源:request_test.go


示例16: body

func body(obj interface{}, raw *string) *string {
	if obj != nil {
		bs, _ := api.Encode(obj)
		body := string(bs)
		return &body
	}
	return raw
}
开发者ID:jamesblunt,项目名称:kubernetes,代码行数:8,代码来源:client_test.go


示例17: write

func (server *ApiServer) write(statusCode int, object interface{}, w http.ResponseWriter) {
	w.WriteHeader(statusCode)
	output, err := api.Encode(object)
	if err != nil {
		server.error(err, w)
		return
	}
	w.Write(output)
}
开发者ID:jmoretti,项目名称:kubernetes,代码行数:9,代码来源:apiserver.go


示例18: doError

func (s *ProxyServer) doError(w http.ResponseWriter, err error) {
	w.WriteHeader(http.StatusInternalServerError)
	w.Header().Add("Content-type", "application/json")
	data, _ := api.Encode(api.Status{
		Status:  api.StatusFailure,
		Details: fmt.Sprintf("internal error: %#v", err),
	})
	w.Write(data)
}
开发者ID:hknochi,项目名称:kubernetes,代码行数:9,代码来源:proxy_server.go


示例19: TestOpGet

func TestOpGet(t *testing.T) {
	simpleStorage := &SimpleRESTStorage{}
	handler := New(map[string]RESTStorage{
		"foo": simpleStorage,
	}, "/prefix/version")
	handler.asyncOpWait = 0
	server := httptest.NewServer(handler)
	client := http.Client{}

	simple := Simple{
		Name: "foo",
	}
	data, err := api.Encode(simple)
	t.Log(string(data))
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	request, err := http.NewRequest("POST", server.URL+"/prefix/version/foo", bytes.NewBuffer(data))
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	response, err := client.Do(request)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if response.StatusCode != http.StatusAccepted {
		t.Errorf("Unexpected response %#v", response)
	}

	var itemOut api.Status
	body, err := extractBody(response, &itemOut)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if itemOut.Status != api.StatusWorking || itemOut.Details == "" {
		t.Errorf("Unexpected status: %#v (%s)", itemOut, string(body))
	}

	req2, err := http.NewRequest("GET", server.URL+"/prefix/version/operations/"+itemOut.Details, nil)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	_, err = client.Do(req2)
	if err != nil {
		t.Errorf("unexpected error: %v", err)
	}

	if response.StatusCode != http.StatusAccepted {
		t.Errorf("Unexpected response %#v", response)
	}
}
开发者ID:Barba-studio,项目名称:kubernetes,代码行数:56,代码来源:operation_test.go


示例20: write

func (server *APIServer) write(statusCode int, object interface{}, w http.ResponseWriter) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(statusCode)
	output, err := api.Encode(object)
	if err != nil {
		server.error(err, w)
		return
	}
	w.Write(output)
}
开发者ID:RubanDeventhiran,项目名称:kubernetes,代码行数:10,代码来源:apiserver.go



注:本文中的github.com/GoogleCloudPlatform/kubernetes/pkg/api.Encode函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang api.EncodeOrDie函数代码示例发布时间:2022-05-23
下一篇:
Golang api.DecodeInto函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap