当前位置: 首页>>代码示例>>Golang>>正文


Golang form.EncodeToValues函数代码示例

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


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

示例1: TestNodeContainerCreateInvalid

func (s *S) TestNodeContainerCreateInvalid(c *check.C) {
	reader := strings.NewReader("")
	request, err := http.NewRequest("POST", "/1.2/nodecontainers", reader)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	recorder := httptest.NewRecorder()
	server := RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusBadRequest)
	c.Assert(recorder.Body.String(), check.Matches, "node container config name cannot be empty\n")
	values, err := form.EncodeToValues(nodecontainer.NodeContainerConfig{Name: ""})
	c.Assert(err, check.IsNil)
	reader = strings.NewReader(values.Encode())
	request, err = http.NewRequest("POST", "/1.2/nodecontainers", reader)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	recorder = httptest.NewRecorder()
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusBadRequest)
	c.Assert(recorder.Body.String(), check.Matches, "node container config name cannot be empty\n")
	values, err = form.EncodeToValues(nodecontainer.NodeContainerConfig{Name: "x1"})
	c.Assert(err, check.IsNil)
	reader = strings.NewReader(values.Encode())
	request, err = http.NewRequest("POST", "/1.2/nodecontainers", reader)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	recorder = httptest.NewRecorder()
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusBadRequest)
	c.Assert(recorder.Body.String(), check.Matches, "node container config image cannot be empty\n")
}
开发者ID:tsuru,项目名称:tsuru,代码行数:34,代码来源:nodecontainer_test.go

示例2: TestUpdateNodeEnableAndDisableCantBeDone

func (s *S) TestUpdateNodeEnableAndDisableCantBeDone(c *check.C) {
	err := s.provisioner.AddNode(provision.AddNodeOptions{
		Address: "localhost:1999",
	})
	c.Assert(err, check.IsNil)
	opts := provision.AddPoolOptions{Name: "pool1"}
	err = provision.AddPool(opts)
	c.Assert(err, check.IsNil)
	defer provision.RemovePool("pool1")
	params := provision.UpdateNodeOptions{
		Address: "localhost:1999",
		Enable:  true,
		Disable: true,
	}
	v, err := form.EncodeToValues(&params)
	c.Assert(err, check.IsNil)
	b := strings.NewReader(v.Encode())
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("PUT", "/node", b)
	c.Assert(err, check.IsNil)
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusBadRequest)
	c.Assert(recorder.Body.String(), check.Equals, "A node can't be enabled and disabled simultaneously.\n")
}
开发者ID:tsuru,项目名称:tsuru,代码行数:27,代码来源:node_test.go

示例3: TestAutoScaleSetRuleInvalidRule

func (s *HandlersSuite) TestAutoScaleSetRuleInvalidRule(c *check.C) {
	rule := autoScaleRule{MetadataFilter: "pool1", Enabled: true, ScaleDownRatio: 0.9, MaxMemoryRatio: 2.0}
	v, err := form.EncodeToValues(&rule)
	c.Assert(err, check.IsNil)
	body := strings.NewReader(v.Encode())
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("POST", "/docker/autoscale/rules", body)
	c.Assert(err, check.IsNil)
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusInternalServerError)
	c.Assert(recorder.Body.String(), check.Matches, "(?s).*invalid rule, scale down ratio needs to be greater than 1.0, got 0.9.*")
	c.Assert(eventtest.EventDesc{
		Target: event.Target{Type: event.TargetTypePool, Value: "pool1"},
		Owner:  s.token.GetUserName(),
		Kind:   "node.autoscale.update",
		StartCustomData: []map[string]interface{}{
			{"name": "MetadataFilter", "value": "pool1"},
			{"name": "Enabled", "value": "true"},
			{"name": "ScaleDownRatio", "value": "0.9"},
			{"name": "MaxMemoryRatio", "value": "2"},
		},
		ErrorMatches: `.*invalid rule, scale down ratio needs to be greater than 1.0, got 0.9.*`,
	}, eventtest.HasEvent)
}
开发者ID:tsuru,项目名称:tsuru,代码行数:27,代码来源:handlers_test.go

示例4: Run

func (c *rebalanceContainersCmd) Run(context *cmd.Context, client *cmd.Client) error {
	context.RawOutput()
	if !c.dry && !c.Confirm(context, "Are you sure you want to rebalance containers?") {
		return nil
	}
	u, err := cmd.GetURL("/docker/containers/rebalance")
	if err != nil {
		return err
	}
	opts := rebalanceOptions{
		Dry: c.dry,
	}
	if len(c.metadataFilter) > 0 {
		opts.MetadataFilter = c.metadataFilter
	}
	if len(c.appFilter) > 0 {
		opts.AppFilter = c.appFilter
	}
	v, err := form.EncodeToValues(&opts)
	if err != nil {
		return err
	}
	request, err := http.NewRequest("POST", u, bytes.NewBufferString(v.Encode()))
	if err != nil {
		return err
	}
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	response, err := client.Do(request)
	if err != nil {
		return err
	}
	return cmd.StreamJSONResponse(context.Stdout, response)
}
开发者ID:tsuru,项目名称:tsuru,代码行数:33,代码来源:admin.go

示例5: TestUpdateNodeEnableNodeHandler

func (s *S) TestUpdateNodeEnableNodeHandler(c *check.C) {
	err := s.provisioner.AddNode(provision.AddNodeOptions{
		Address: "localhost:1999",
	})
	c.Assert(err, check.IsNil)
	opts := provision.AddPoolOptions{Name: "pool1"}
	err = provision.AddPool(opts)
	c.Assert(err, check.IsNil)
	defer provision.RemovePool("pool1")
	params := provision.UpdateNodeOptions{
		Address: "localhost:1999",
		Enable:  true,
	}
	v, err := form.EncodeToValues(&params)
	c.Assert(err, check.IsNil)
	b := strings.NewReader(v.Encode())
	recorder := httptest.NewRecorder()
	request, err := http.NewRequest("PUT", "/node", b)
	c.Assert(err, check.IsNil)
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	server := RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	nodes, err := s.provisioner.ListNodes(nil)
	c.Assert(err, check.IsNil)
	c.Assert(nodes, check.HasLen, 1)
	c.Assert(nodes[0].Status(), check.Equals, "enabled")
}
开发者ID:tsuru,项目名称:tsuru,代码行数:29,代码来源:node_test.go

示例6: WithForm

// WithForm sets Content-Type header to "application/x-www-form-urlencoded"
// or (if WithMultipart() was called) "multipart/form-data", converts given
// object to url.Values using github.com/ajg/form, and adds it to request body.
//
// Various object types are supported, including maps and structs. Structs may
// contain "form" struct tag, similar to "json" struct tag for json.Marshal().
// See https://github.com/ajg/form for details.
//
// Multiple WithForm(), WithFormField(), and WithFile() calls may be combined.
// If WithMultipart() is called, it should be called first.
//
// Example:
//  type MyForm struct {
//      Foo int `form:"foo"`
//  }
//
//  req := NewRequest(config, "PUT", "http://example.com/path")
//  req.WithForm(MyForm{Foo: 123})
//
//  req := NewRequest(config, "PUT", "http://example.com/path")
//  req.WithForm(map[string]interface{}{"foo": 123})
func (r *Request) WithForm(object interface{}) *Request {
	f, err := form.EncodeToValues(object)
	if err != nil {
		r.chain.fail(err.Error())
		return r
	}

	if r.multipart != nil {
		r.setType("WithForm", "multipart/form-data", false)

		var keys []string
		for k := range f {
			keys = append(keys, k)
		}
		sort.Strings(keys)
		for _, k := range keys {
			if err := r.multipart.WriteField(k, f[k][0]); err != nil {
				r.chain.fail(err.Error())
				return r
			}
		}
	} else {
		r.setType("WithForm", "application/x-www-form-urlencoded", false)

		if r.form == nil {
			r.form = make(url.Values)
		}
		for k, v := range f {
			r.form[k] = append(r.form[k], v...)
		}
	}

	return r
}
开发者ID:stellar,项目名称:bridge-server,代码行数:55,代码来源:request.go

示例7: TestNodeContainerUpdateLimited

func (s *S) TestNodeContainerUpdateLimited(c *check.C) {
	err := nodecontainer.AddNewContainer("p1", &nodecontainer.NodeContainerConfig{Name: "c1", Config: docker.Config{Image: "img1"}})
	c.Assert(err, check.IsNil)
	t := userWithPermission(c, permission.Permission{
		Scheme:  permission.PermNodecontainerUpdate,
		Context: permission.Context(permission.CtxPool, "p1"),
	})
	values, err := form.EncodeToValues(nodecontainer.NodeContainerConfig{Name: "c1"})
	c.Assert(err, check.IsNil)
	reader := strings.NewReader(values.Encode())
	request, err := http.NewRequest("POST", "/1.2/nodecontainers/c1", reader)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+t.GetValue())
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	recorder := httptest.NewRecorder()
	server := RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusForbidden)
	values.Set("pool", "p1")
	reader = strings.NewReader(values.Encode())
	request, err = http.NewRequest("POST", "/1.2/nodecontainers/c1", reader)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+t.GetValue())
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	recorder = httptest.NewRecorder()
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
}
开发者ID:tsuru,项目名称:tsuru,代码行数:28,代码来源:nodecontainer_test.go

示例8: WithQueryObject

// WithQueryObject adds multiple query parameters to request URL.
//
// object is converted to query string using github.com/google/go-querystring
// if it's a struct or pointer to struct, or github.com/ajg/form otherwise.
//
// Various object types are supported. Structs may contain "url" struct tag,
// similar to "json" struct tag for json.Marshal().
//
// Example:
//  type MyURL struct {
//      A int    `url:"a"`
//      B string `url:"b"`
//  }
//
//  req := NewRequest(config, "PUT", "http://example.com/path")
//  req.WithQueryObject(MyURL{A: 123, B: "foo"})
//  // URL is now http://example.com/path?a=123&b=foo
//
//  req := NewRequest(config, "PUT", "http://example.com/path")
//  req.WithQueryObject(map[string]interface{}{"a": 123, "b": "foo"})
//  // URL is now http://example.com/path?a=123&b=foo
func (r *Request) WithQueryObject(object interface{}) *Request {
	if object == nil {
		return r
	}
	var (
		q   url.Values
		err error
	)
	if reflect.Indirect(reflect.ValueOf(object)).Kind() == reflect.Struct {
		q, err = query.Values(object)
		if err != nil {
			r.chain.fail(err.Error())
			return r
		}
	} else {
		q, err = form.EncodeToValues(object)
		if err != nil {
			r.chain.fail(err.Error())
			return r
		}
	}
	if r.query == nil {
		r.query = make(url.Values)
	}
	for k, v := range q {
		r.query[k] = append(r.query[k], v...)
	}
	return r
}
开发者ID:stellar,项目名称:bridge-server,代码行数:50,代码来源:request.go

示例9: Run

func (c *autoScaleSetRuleCmd) Run(context *cmd.Context, client *cmd.Client) error {
	if (c.enable && c.disable) || (!c.enable && !c.disable) {
		return errors.New("either --disable or --enable must be set")
	}
	rule := autoScaleRule{
		MetadataFilter:    c.filterValue,
		MaxContainerCount: c.maxContainerCount,
		MaxMemoryRatio:    float32(c.maxMemoryRatio),
		ScaleDownRatio:    float32(c.scaleDownRatio),
		PreventRebalance:  c.noRebalanceOnScale,
		Enabled:           c.enable,
	}
	val, err := form.EncodeToValues(rule)
	if err != nil {
		return err
	}
	body := strings.NewReader(val.Encode())
	u, err := cmd.GetURL("/docker/autoscale/rules")
	if err != nil {
		return err
	}
	req, err := http.NewRequest("POST", u, body)
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	_, err = client.Do(req)
	if err != nil {
		return err
	}
	fmt.Fprintln(context.Stdout, "Rule successfully defined.")
	return nil
}
开发者ID:tsuru,项目名称:tsuru,代码行数:33,代码来源:cmd.go

示例10: TestAddNodeHandlerExisting

func (s *S) TestAddNodeHandlerExisting(c *check.C) {
	opts := provision.AddPoolOptions{Name: "pool1"}
	err := provision.AddPool(opts)
	c.Assert(err, check.IsNil)
	defer provision.RemovePool("pool1")
	serverAddr := "http://mysrv1"
	params := provision.AddNodeOptions{
		Register: true,
		Metadata: map[string]string{
			"address": serverAddr,
			"pool":    "pool1",
		},
	}
	v, err := form.EncodeToValues(&params)
	c.Assert(err, check.IsNil)
	req, err := http.NewRequest("POST", "/1.2/node", strings.NewReader(v.Encode()))
	c.Assert(err, check.IsNil)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", s.token.GetValue())
	rec := httptest.NewRecorder()
	m := RunServer(true)
	m.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusCreated)
	req, err = http.NewRequest("POST", "/1.2/node", strings.NewReader(v.Encode()))
	c.Assert(err, check.IsNil)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", s.token.GetValue())
	rec = httptest.NewRecorder()
	m.ServeHTTP(rec, req)
	var result map[string]string
	err = json.NewDecoder(rec.Body).Decode(&result)
	c.Assert(err, check.IsNil)
	c.Assert(result["Error"], check.Equals, "node with address \"http://mysrv1\" already exists in provisioner \"fake\"")
	c.Assert(rec.Code, check.Equals, http.StatusCreated)
}
开发者ID:tsuru,项目名称:tsuru,代码行数:35,代码来源:node_test.go

示例11: RequestForm

// RequestForm makes an HTTP request with the given interface being encoded as
// form data.
func (c *Client) RequestForm(verb, p string, i interface{}, ro *RequestOptions) (*http.Response, error) {
	values, err := form.EncodeToValues(i)
	if err != nil {
		return nil, err
	}

	if ro == nil {
		ro = new(RequestOptions)
	}

	if ro.Headers == nil {
		ro.Headers = make(map[string]string)
	}
	ro.Headers["Content-Type"] = "application/x-www-form-urlencoded"

	// There is a super-jank implementation in the form library where fields with
	// a "dot" are replaced with "/.". That is then URL encoded and Fastly just
	// dies. We fix that here.
	body := strings.Replace(values.Encode(), "%5C.", ".", -1)

	ro.Body = strings.NewReader(body)
	ro.BodyLength = int64(len(body))

	return c.Request(verb, p, ro)
}
开发者ID:RezaDKhan,项目名称:terraform,代码行数:27,代码来源:client.go

示例12: TestAddNodeHandlerWithInvalidURLAddress

func (s *S) TestAddNodeHandlerWithInvalidURLAddress(c *check.C) {
	opts := provision.AddPoolOptions{Name: "pool1"}
	err := provision.AddPool(opts)
	c.Assert(err, check.IsNil)
	params := provision.AddNodeOptions{
		Register: true,
		Metadata: map[string]string{
			"address": "/invalid",
			"pool":    "pool1",
		},
	}
	v, err := form.EncodeToValues(&params)
	c.Assert(err, check.IsNil)
	b := strings.NewReader(v.Encode())
	req, err := http.NewRequest("POST", "/node", b)
	c.Assert(err, check.IsNil)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", s.token.GetValue())
	rec := httptest.NewRecorder()
	m := RunServer(true)
	m.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusCreated)
	var result map[string]string
	err = json.NewDecoder(rec.Body).Decode(&result)
	c.Assert(err, check.IsNil)
	c.Assert(result["Error"], check.Equals, "Invalid address url: host cannot be empty")
	params = provision.AddNodeOptions{
		Register: true,
		Metadata: map[string]string{
			"address": "xxx://abc/invalid",
			"pool":    "pool1",
		},
	}
	v, err = form.EncodeToValues(&params)
	c.Assert(err, check.IsNil)
	b = strings.NewReader(v.Encode())
	req, err = http.NewRequest("POST", "/node", b)
	c.Assert(err, check.IsNil)
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Authorization", s.token.GetValue())
	rec = httptest.NewRecorder()
	m.ServeHTTP(rec, req)
	c.Assert(rec.Code, check.Equals, http.StatusCreated)
	err = json.NewDecoder(rec.Body).Decode(&result)
	c.Assert(err, check.IsNil)
	c.Assert(result["Error"], check.Equals, "Invalid address url: scheme must be http[s]")
}
开发者ID:tsuru,项目名称:tsuru,代码行数:47,代码来源:node_test.go

示例13: encodeToForm

func (o *HTTP) encodeToForm(record intf.Record) string {
	values, err := form.EncodeToValues(record)
	if err != nil {
		Error("Form Error %s", err)
	}

	return values.Encode()
}
开发者ID:ikanor,项目名称:harvester,代码行数:8,代码来源:http.go

示例14: TestRebalanceContainersDryBodyHandler

func (s *S) TestRebalanceContainersDryBodyHandler(c *check.C) {
	p, err := s.startMultipleServersCluster()
	c.Assert(err, check.IsNil)
	mainDockerProvisioner = p
	err = s.newFakeImage(p, "tsuru/app-myapp", nil)
	c.Assert(err, check.IsNil)
	appInstance := provisiontest.NewFakeApp("myapp", "python", 0)
	defer p.Destroy(appInstance)
	p.Provision(appInstance)
	coll := p.Collection()
	defer coll.Close()
	coll.Insert(container.Container{ID: "container-id", AppName: appInstance.GetName(), Version: "container-version", Image: "tsuru/python", ProcessName: "web"})
	defer coll.RemoveAll(bson.M{"appname": appInstance.GetName()})
	imageId, err := image.AppCurrentImageName(appInstance.GetName())
	c.Assert(err, check.IsNil)
	units, err := addContainersWithHost(&changeUnitsPipelineArgs{
		toHost:      "localhost",
		toAdd:       map[string]*containersToAdd{"web": {Quantity: 5}},
		app:         appInstance,
		imageId:     imageId,
		provisioner: p,
	})
	c.Assert(err, check.IsNil)
	appStruct := &app.App{
		Name:     appInstance.GetName(),
		Platform: appInstance.GetPlatform(),
		Pool:     "test-default",
	}
	err = s.storage.Apps().Insert(appStruct)
	c.Assert(err, check.IsNil)
	err = s.storage.Apps().Update(
		bson.M{"name": appStruct.Name},
		bson.M{"$set": bson.M{"units": units}},
	)
	c.Assert(err, check.IsNil)
	recorder := httptest.NewRecorder()
	opts := rebalanceOptions{Dry: true}
	v, err := form.EncodeToValues(&opts)
	c.Assert(err, check.IsNil)
	b := strings.NewReader(v.Encode())
	request, err := http.NewRequest("POST", "/docker/containers/rebalance", b)
	c.Assert(err, check.IsNil)
	request.Header.Set("Authorization", "bearer "+s.token.GetValue())
	request.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	server := api.RunServer(true)
	server.ServeHTTP(recorder, request)
	c.Assert(recorder.Code, check.Equals, http.StatusOK)
	body, err := ioutil.ReadAll(recorder.Body)
	c.Assert(err, check.IsNil)
	validJson := fmt.Sprintf("[%s]", strings.Replace(strings.Trim(string(body), "\n "), "\n", ",", -1))
	var result []tsuruIo.SimpleJsonMessage
	err = json.Unmarshal([]byte(validJson), &result)
	c.Assert(err, check.IsNil)
	c.Assert(result, check.HasLen, 8)
	c.Assert(result[0].Message, check.Equals, "Rebalancing 6 units...\n")
	c.Assert(result[1].Message, check.Matches, "(?s)Would move unit .*")
	c.Assert(result[7].Message, check.Equals, "Containers successfully rebalanced!\n")
}
开发者ID:tsuru,项目名称:tsuru,代码行数:58,代码来源:handlers_test.go

示例15: FormData

// FormData ecodes from data from an interface{} and converts to an `io.Reader`.
func FormData(data interface{}) (io.Reader, error) {
	values, err := form.EncodeToValues(data)
	if err != nil {
		return nil, err
	}

	body := bytes.NewBufferString(values.Encode())
	return body, nil
}
开发者ID:meshhq,项目名称:gohttp,代码行数:10,代码来源:data.go


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