本文整理汇总了Golang中github.com/GoogleCloudPlatform/kubernetes/pkg/runtime.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, _ := runtime.Encode(reqObj)
expectedObj := &api.Service{Port: 12345}
expectedBody, _ := runtime.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:hungld,项目名称:kubernetes,代码行数:35,代码来源:request_test.go
示例2: TestDoRequestAcceptedSuccess
func TestDoRequestAcceptedSuccess(t *testing.T) {
status := api.Status{Status: api.StatusSuccess}
expectedBody, _ := runtime.Encode(status)
fakeHandler := util.FakeHandler{
StatusCode: 202,
ResponseBody: string(expectedBody),
T: t,
}
testServer := httptest.NewServer(&fakeHandler)
request, _ := http.NewRequest("GET", testServer.URL+"/foo/bar", nil)
auth := AuthInfo{User: "user", Password: "pass"}
c, err := New(testServer.URL, &auth)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
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 := runtime.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:K-A-Z,项目名称:kubernetes,代码行数:31,代码来源:client_test.go
示例3: 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.
// If obj is an io.Reader, use 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 = t
default:
data, err := runtime.Encode(obj)
if err != nil {
r.err = err
return r
}
r.body = bytes.NewBuffer(data)
}
return r
}
开发者ID:hungld,项目名称:kubernetes,代码行数:31,代码来源:request.go
示例4: 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 := runtime.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 := runtime.Encode(expectedType)
if err != nil {
t.Errorf("Could not encode object: %v", err)
continue
}
t.Logf("Found pod %s\n%s", json, encoded)
}
}
开发者ID:K-A-Z,项目名称:kubernetes,代码行数:28,代码来源:examples_test.go
示例5: 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 := runtime.Encode(obj)
if err != nil {
return err
}
return i.Print(data, output)
}
开发者ID:K-A-Z,项目名称:kubernetes,代码行数:8,代码来源:resource_printer.go
示例6: TestPolling
func TestPolling(t *testing.T) {
objects := []interface{}{
&api.Status{Status: api.StatusWorking, Details: &api.StatusDetails{ID: "1234"}},
&api.Status{Status: api.StatusWorking, Details: &api.StatusDetails{ID: "1234"}},
&api.Status{Status: api.StatusWorking, Details: &api.StatusDetails{ID: "1234"}},
&api.Status{Status: api.StatusWorking, Details: &api.StatusDetails{ID: "1234"}},
&api.Status{Status: api.StatusSuccess},
}
callNumber := 0
testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, err := runtime.Encode(objects[callNumber])
if err != nil {
t.Errorf("Unexpected encode error")
}
callNumber++
w.Write(data)
}))
auth := AuthInfo{User: "user", Password: "pass"}
c := NewOrDie(testServer.URL, &auth)
trials := []func(){
func() {
// Check that we do indeed poll when asked to.
obj, err := c.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 := c.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:hungld,项目名称:kubernetes,代码行数:59,代码来源:request_test.go
示例7: body
func body(obj interface{}, raw *string) *string {
if obj != nil {
bs, _ := runtime.Encode(obj)
body := string(bs)
return &body
}
return raw
}
开发者ID:K-A-Z,项目名称:kubernetes,代码行数:8,代码来源:client_test.go
示例8: doError
func (s *ProxyServer) doError(w http.ResponseWriter, err error) {
w.WriteHeader(http.StatusInternalServerError)
w.Header().Add("Content-type", "application/json")
data, _ := runtime.Encode(api.Status{
Status: api.StatusFailure,
Message: fmt.Sprintf("internal error: %#v", err),
})
w.Write(data)
}
开发者ID:K-A-Z,项目名称:kubernetes,代码行数:9,代码来源:proxy_server.go
示例9: TestCreateReplica
func TestCreateReplica(t *testing.T) {
body, _ := runtime.Encode(api.Pod{})
fakeHandler := util.FakeHandler{
StatusCode: 200,
ResponseBody: string(body),
}
testServer := httptest.NewTLSServer(&fakeHandler)
client := client.NewOrDie(testServer.URL, nil)
podControl := RealPodControl{
kubeClient: client,
}
controllerSpec := api.ReplicationController{
JSONBase: api.JSONBase{
Kind: "ReplicationController",
},
DesiredState: api.ReplicationControllerState{
PodTemplate: api.PodTemplate{
DesiredState: api.PodState{
Manifest: api.ContainerManifest{
Containers: []api.Container{
{
Image: "foo/bar",
},
},
},
},
Labels: map[string]string{
"name": "foo",
"type": "production",
},
},
},
}
podControl.createReplica(controllerSpec)
expectedPod := api.Pod{
JSONBase: api.JSONBase{
Kind: "Pod",
APIVersion: "v1beta1",
},
Labels: controllerSpec.DesiredState.PodTemplate.Labels,
DesiredState: controllerSpec.DesiredState.PodTemplate.DesiredState,
}
fakeHandler.ValidateRequest(t, makeURL("/pods"), "POST", nil)
actualPod := api.Pod{}
if err := json.Unmarshal([]byte(fakeHandler.RequestBody), &actualPod); err != nil {
t.Errorf("Unexpected error: %#v", err)
}
if !reflect.DeepEqual(expectedPod, actualPod) {
t.Logf("Body: %s", fakeHandler.RequestBody)
t.Errorf("Unexpected mismatch. Expected\n %#v,\n Got:\n %#v", expectedPod, actualPod)
}
}
开发者ID:K-A-Z,项目名称:kubernetes,代码行数:56,代码来源:replication_controller_test.go
示例10: ToWireFormat
// ToWireFormat takes input 'data' as either json or yaml, checks that it parses as the
// appropriate object type, and returns json for sending to the API or an error.
func (p *Parser) ToWireFormat(data []byte, storage string) ([]byte, error) {
prototypeType, found := p.storageToType[storage]
if !found {
return nil, fmt.Errorf("unknown storage type: %v", storage)
}
obj := reflect.New(prototypeType).Interface()
err := runtime.DecodeInto(data, obj)
if err != nil {
return nil, err
}
return runtime.Encode(obj)
}
开发者ID:K-A-Z,项目名称:kubernetes,代码行数:15,代码来源:parse.go
示例11: TestEncode_Ptr
func TestEncode_Ptr(t *testing.T) {
pod := &api.Pod{
Labels: map[string]string{"name": "foo"},
}
obj := interface{}(pod)
data, err := runtime.Encode(obj)
obj2, err2 := runtime.Decode(data)
if err != nil || err2 != nil {
t.Fatalf("Failure: '%v' '%v'", err, err2)
}
if _, ok := obj2.(*api.Pod); !ok {
t.Fatalf("Got wrong type")
}
if !reflect.DeepEqual(obj2, pod) {
t.Errorf("Expected:\n %#v,\n Got:\n %#v", &pod, obj2)
}
}
开发者ID:K-A-Z,项目名称:kubernetes,代码行数:17,代码来源:serialization_test.go
示例12: TestSyncReplicationControllerCreates
func TestSyncReplicationControllerCreates(t *testing.T) {
body, _ := runtime.Encode(newPodList(0))
fakeHandler := util.FakeHandler{
StatusCode: 200,
ResponseBody: string(body),
}
testServer := httptest.NewTLSServer(&fakeHandler)
client := client.NewOrDie(testServer.URL, nil)
fakePodControl := FakePodControl{}
manager := NewReplicationManager(client)
manager.podControl = &fakePodControl
controllerSpec := newReplicationController(2)
manager.syncReplicationController(controllerSpec)
validateSyncReplication(t, &fakePodControl, 2, 0)
}
开发者ID:K-A-Z,项目名称:kubernetes,代码行数:19,代码来源:replication_controller_test.go
示例13: runTest
func runTest(t *testing.T, source interface{}) {
name := reflect.TypeOf(source).Elem().Name()
apiObjectFuzzer.Fuzz(source)
j, err := runtime.FindJSONBase(source)
if err != nil {
t.Fatalf("Unexpected error %v for %#v", err, source)
}
j.SetKind("")
j.SetAPIVersion("")
data, err := runtime.Encode(source)
if err != nil {
t.Errorf("%v: %v (%#v)", name, err, source)
return
}
obj2, err := runtime.Decode(data)
if err != nil {
t.Errorf("%v: %v", name, err)
return
} else {
if !reflect.DeepEqual(source, obj2) {
t.Errorf("1: %v: diff: %v", name, objDiff(source, obj2))
return
}
}
obj3 := reflect.New(reflect.TypeOf(source).Elem()).Interface()
err = runtime.DecodeInto(data, obj3)
if err != nil {
t.Errorf("2: %v: %v", name, err)
return
} else {
if !reflect.DeepEqual(source, obj3) {
t.Errorf("3: %v: diff: %v", name, objDiff(source, obj3))
return
}
}
}
开发者ID:K-A-Z,项目名称:kubernetes,代码行数:38,代码来源:serialization_test.go
示例14: TestNewBindingStorage
func TestNewBindingStorage(t *testing.T) {
mockRegistry := MockRegistry{
OnApplyBinding: func(b *api.Binding) error { return nil },
}
b := NewBindingStorage(mockRegistry)
binding := &api.Binding{
PodID: "foo",
Host: "bar",
}
body, err := runtime.Encode(binding)
if err != nil {
t.Fatalf("Unexpected encode error %v", err)
}
obj := b.New()
err = runtime.DecodeInto(body, obj)
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
if e, a := binding, obj; !reflect.DeepEqual(e, a) {
t.Errorf("Expected %#v, but got %#v", e, a)
}
}
开发者ID:K-A-Z,项目名称:kubernetes,代码行数:23,代码来源:storage_test.go
示例15: DoParseTest
func DoParseTest(t *testing.T, storage string, obj interface{}, p *Parser) {
jsonData, _ := runtime.Encode(obj)
yamlData, _ := yaml.Marshal(obj)
t.Logf("Intermediate yaml:\n%v\n", string(yamlData))
t.Logf("Intermediate json:\n%v\n", string(jsonData))
jsonGot, jsonErr := p.ToWireFormat(jsonData, storage)
yamlGot, yamlErr := p.ToWireFormat(yamlData, storage)
if jsonErr != nil {
t.Errorf("json err: %#v", jsonErr)
}
if yamlErr != nil {
t.Errorf("yaml err: %#v", yamlErr)
}
if string(jsonGot) != string(jsonData) {
t.Errorf("json output didn't match:\nGot:\n%v\n\nWanted:\n%v\n",
string(jsonGot), string(jsonData))
}
if string(yamlGot) != string(jsonData) {
t.Errorf("yaml parsed output didn't match:\nGot:\n%v\n\nWanted:\n%v\n",
string(yamlGot), string(jsonData))
}
}
开发者ID:K-A-Z,项目名称:kubernetes,代码行数:23,代码来源:parse_test.go
示例16: TestControllerDecode
func TestControllerDecode(t *testing.T) {
mockRegistry := registrytest.ControllerRegistry{}
storage := RegistryStorage{
registry: &mockRegistry,
}
controller := &api.ReplicationController{
JSONBase: api.JSONBase{
ID: "foo",
},
}
body, err := runtime.Encode(controller)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
controllerOut := storage.New()
if err := runtime.DecodeInto(body, controllerOut); err != nil {
t.Errorf("unexpected error: %v", err)
}
if !reflect.DeepEqual(controller, controllerOut) {
t.Errorf("Expected %#v, found %#v", controller, controllerOut)
}
}
开发者ID:hungld,项目名称:kubernetes,代码行数:24,代码来源:storage_test.go
示例17: TestDoRequestAccepted
func TestDoRequestAccepted(t *testing.T) {
status := api.Status{Status: api.StatusWorking}
expectedBody, _ := runtime.Encode(status)
fakeHandler := util.FakeHandler{
StatusCode: 202,
ResponseBody: string(expectedBody),
T: t,
}
testServer := httptest.NewServer(&fakeHandler)
request, _ := http.NewRequest("GET", testServer.URL+"/foo/bar", nil)
auth := AuthInfo{User: "user", Password: "pass"}
c, err := New(testServer.URL, &auth)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
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:K-A-Z,项目名称:kubernetes,代码行数:36,代码来源:client_test.go
示例18: TestPodDecode
func TestPodDecode(t *testing.T) {
podRegistry := registrytest.NewPodRegistry(nil)
storage := RegistryStorage{
registry: podRegistry,
}
expected := &api.Pod{
JSONBase: api.JSONBase{
ID: "foo",
},
}
body, err := runtime.Encode(expected)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
actual := storage.New()
if err := runtime.DecodeInto(body, actual); err != nil {
t.Errorf("unexpected error: %v", err)
}
if !reflect.DeepEqual(expected, actual) {
t.Errorf("Expected %#v, Got %#v", expected, actual)
}
}
开发者ID:hungld,项目名称:kubernetes,代码行数:24,代码来源:storage_test.go
示例19: TestBuildDecode
func TestBuildDecode(t *testing.T) {
mockRegistry := test.BuildRegistry{}
storage := Storage{
registry: &mockRegistry,
}
build := &api.Build{
JSONBase: kubeapi.JSONBase{
ID: "foo",
},
}
body, err := runtime.Encode(build)
if err != nil {
t.Errorf("unexpected error: %v", err)
}
buildOut := storage.New()
if err := runtime.DecodeInto(body, buildOut); err != nil {
t.Errorf("unexpected error: %v", err)
}
if !reflect.DeepEqual(build, buildOut) {
t.Errorf("Expected %#v, found %#v", build, buildOut)
}
}
开发者ID:lmiccini,项目名称:origin,代码行数:24,代码来源:storage_test.go
示例20: executeAPIRequest
func (c *KubeConfig) executeAPIRequest(method string, clients map[string]RESTClient) bool {
storage, path, hasSuffix := storagePathFromArg(c.Arg(1))
validStorage := checkStorage(storage)
client, ok := clients[storage]
if !ok {
glog.Fatalf("Unsupported storage type %s", storage)
}
verb := ""
setBody := false
var version uint64
switch method {
case "get":
verb = "GET"
if !validStorage || !hasSuffix {
glog.Fatalf("usage: kubecfg [OPTIONS] %s <%s>[/<id>]", method, prettyWireStorage())
}
case "list":
verb = "GET"
if !validStorage || hasSuffix {
glog.Fatalf("usage: kubecfg [OPTIONS] %s <%s>", method, prettyWireStorage())
}
case "delete":
verb = "DELETE"
if !validStorage || !hasSuffix {
glog.Fatalf("usage: kubecfg [OPTIONS] %s <%s>/<id>", method, prettyWireStorage())
}
case "create":
verb = "POST"
setBody = true
if !validStorage || hasSuffix {
glog.Fatalf("usage: kubecfg [OPTIONS] %s <%s>", method, prettyWireStorage())
}
case "update":
obj, err := client.Verb("GET").Path(path).Do().Get()
if err != nil {
glog.Fatalf("error obtaining resource version for update: %v", err)
}
jsonBase, err := runtime.FindJSONBase(obj)
if err != nil {
glog.Fatalf("error finding json base for update: %v", err)
}
version = jsonBase.ResourceVersion()
verb = "PUT"
setBody = true
if !validStorage || !hasSuffix {
glog.Fatalf("usage: kubecfg [OPTIONS] %s <%s>/<id>", method, prettyWireStorage())
}
default:
return false
}
r := client.Verb(verb).
Path(path).
ParseSelectorParam("labels", c.Selector)
if setBody {
if version != 0 {
data := c.readConfig(storage)
obj, err := runtime.Decode(data)
if err != nil {
glog.Fatalf("error setting resource version: %v", err)
}
jsonBase, err := runtime.FindJSONBase(obj)
if err != nil {
glog.Fatalf("error setting resource version: %v", err)
}
jsonBase.SetResourceVersion(version)
data, err = runtime.Encode(obj)
if err != nil {
glog.Fatalf("error setting resource version: %v", err)
}
r.Body(data)
} else {
r.Body(c.readConfig(storage))
}
}
result := r.Do()
obj, err := result.Get()
if err != nil {
glog.Fatalf("Got request error: %v\n", err)
return false
}
var printer kubecfg.ResourcePrinter
switch {
case c.JSON:
printer = &kubecfg.IdentityPrinter{}
case c.YAML:
printer = &kubecfg.YAMLPrinter{}
case len(c.TemplateFile) > 0 || len(c.TemplateStr) > 0:
var data []byte
if len(c.TemplateFile) > 0 {
var err error
data, err = ioutil.ReadFile(c.TemplateFile)
if err != nil {
glog.Fatalf("Error reading template %s, %v\n", c.TemplateFile, err)
return false
}
} else {
data = []byte(c.TemplateStr)
//.........这里部分代码省略.........
开发者ID:lmiccini,项目名称:origin,代码行数:101,代码来源:kubecfg.go
注:本文中的github.com/GoogleCloudPlatform/kubernetes/pkg/runtime.Encode函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论