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

Golang xml.Marshal函数代码示例

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

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



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

示例1: startVoting

func startVoting() {
	fmt.Println("Start voting!")
	time.Sleep(time.Second * 10)
	// Send you adress to all. In this case it really doesn't matter
	msg := message.NewVoteMessage(myAddress)
	mm, _ := xml.Marshal(msg)
	_, err := writeMulticast.WriteToUDP(mm, multicastAddr)
	check(err)

	// Wait 10 seconds
	c := time.After(time.Second * 10)
	<-c

	// Check if we got any address that is bigger
	for addr, _ := range knownAddresess {
		if addr > myAddress {
			return
		}
	}

	// Become the server if we are the greatest
	msga := message.NewCoordinatorMessage(string(myAddress))
	mmm, _ := xml.Marshal(msga)
	writeMulticast.WriteToUDP(mmm, multicastAddr)
	fmt.Println("NOW I AM BECOME DEATH")
}
开发者ID:Madrigal,项目名称:GoUDP,代码行数:26,代码来源:election.go


示例2: completeMultipartUploadRequest

// completeMultipartUploadRequest wrapper creates a new CompleteMultipartUpload request
func (a apiCore) completeMultipartUploadRequest(bucket, object, uploadID string, complete completeMultipartUpload) (*request, error) {
	op := &operation{
		HTTPServer: a.config.Endpoint,
		HTTPMethod: "POST",
		HTTPPath:   separator + bucket + separator + object + "?uploadId=" + uploadID,
	}
	var completeMultipartUploadBytes []byte
	var err error
	switch {
	case a.config.AcceptType == "application/xml":
		completeMultipartUploadBytes, err = xml.Marshal(complete)
	case a.config.AcceptType == "application/json":
		completeMultipartUploadBytes, err = json.Marshal(complete)
	default:
		completeMultipartUploadBytes, err = xml.Marshal(complete)
	}
	if err != nil {
		return nil, err
	}
	completeMultipartUploadBuffer := bytes.NewReader(completeMultipartUploadBytes)
	r, err := newRequest(op, a.config, completeMultipartUploadBuffer)
	if err != nil {
		return nil, err
	}
	r.req.ContentLength = int64(completeMultipartUploadBuffer.Len())
	return r, nil
}
开发者ID:henrylee2cn,项目名称:mc,代码行数:28,代码来源:api-multipart-core.go


示例3: Build

// Build builds an Envelope for the specified SOAP version.
func (bldr *EnvBuilder) Build(version string) (Envelope, error) {
	if !isValidVersion(version) {
		return nil, ErrInvalidVersion
	}

	bdy, err := xml.Marshal(bldr.payload)
	if err != nil {
		return nil, err
	}

	var env Envelope = &Envelope11{BodyElem: Body11{PayloadElem: bdy}, Xmlns: bldr.xmlns}
	if version == V12 {
		env = &Envelope12{BodyElem: Body12{PayloadElem: bdy}, Xmlns: bldr.xmlns}
	}

	if len(bldr.headers) > 0 {
		hdr, err := xml.Marshal(bldr.headers)
		if err != nil {
			return nil, err
		}

		if len(hdr) > 0 {
			env.setHeader(&Header{Content: hdr})
		}
	}

	return env, nil
}
开发者ID:Bridgevine,项目名称:soap,代码行数:29,代码来源:envelope_builder.go


示例4: SetBucketLogging

//
// SetBucketLogging 修改Bucket的日志设置。
//
// OSS为您提供自动保存访问日志记录功能。Bucket的拥有者可以开启访问日志记录功能。当一个bucket开启访问日志记录功能后,
// OSS自动将访问这个bucket的请求日志,以小时为单位,按照固定的命名规则,生成一个Object写入用户指定的bucket中。
// 如果您需要更多,请参看 https://help.aliyun.com/document_detail/oss/user_guide/security_management/logging.html
//
// bucketName   需要记录访问日志的Bucket。
// targetBucket 访问日志记录到的Bucket。
// targetPrefix bucketName中需要存储访问日志记录的object前缀。为空记录所有object的访问日志。
//
// error 操作无错误为nil,非nil为错误信息。
//
func (client Client) SetBucketLogging(bucketName, targetBucket, targetPrefix string,
	isEnable bool) error {
	var err error
	var bs []byte
	if isEnable {
		lxml := LoggingXML{}
		lxml.LoggingEnabled.TargetBucket = targetBucket
		lxml.LoggingEnabled.TargetPrefix = targetPrefix
		bs, err = xml.Marshal(lxml)
	} else {
		lxml := loggingXMLEmpty{}
		bs, err = xml.Marshal(lxml)
	}

	if err != nil {
		return err
	}

	buffer := new(bytes.Buffer)
	buffer.Write(bs)
	fmt.Println(isEnable, "; xml: ", string(bs))

	contentType := http.DetectContentType(buffer.Bytes())
	headers := map[string]string{}
	headers[HTTPHeaderContentType] = contentType

	resp, err := client.do("PUT", bucketName, "logging", "logging", headers, buffer)
	if err != nil {
		return err
	}
	defer resp.body.Close()
	return checkRespCode(resp.statusCode, []int{http.StatusOK})
}
开发者ID:pombredanne,项目名称:dockyard,代码行数:46,代码来源:client.go


示例5: handleConnection

func handleConnection(conn net.Conn) {

	b := xml.NewDecoder(conn)
	fmt.Fprintf(conn, `<?xml version='1.0'?>
		<stream:stream
			from='localhost'
			id='abc123'
			to='[email protected]'
			version='1.0'
			xml:lang='en'
			xmlns='jabber:server'
			xmlns:stream='http://etherx.jabber.org/streams'>`)

	fmt.Fprintf(conn, "<stream:features/>")
	for {
		iqData := new(Iq)
		b.Decode(iqData)
		switch iqData.Type {
		case "get":
			r := &Iq{Id: iqData.Id, Type: "result"}
			r.Query = Query{Xmlns: "jabber:iq:auth"}
			output, _ := xml.Marshal(r)
			fmt.Fprintf(conn, string(output))
		case "set":
			// Need to perform auth lookup here
			i := Iq{Id: iqData.Id, Type: "result"}
			output, _ := xml.Marshal(i)
			fmt.Fprintf(conn, string(output))
		default:
			// Nothing
		}
	}

}
开发者ID:GoLangPhilly,项目名称:fireside,代码行数:34,代码来源:core.go


示例6: kvHandler

//http handler to handle http request
func kvHandler(w http.ResponseWriter, r *http.Request) {
	var xcel Xcel
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		fmt.Println(err)
	}
	xml.Unmarshal(body, &xcel)
	fmt.Println(xcel)
	if xcelDB.xcelReplicator.IsLeader() {
		fmt.Println(xcelDB.xcelId, ":  ", xcel)
		ApplyCommandTOSM(&xcel)
		//xcel.ServerResponse = true
		responseXML, _ := xml.Marshal(xcel)
		fmt.Fprintf(w, string(responseXML))
	} else {

		leader := xcelDB.xcelReplicator.GetLeader()
		if leader == 0 {
			xcel.ServerResponse = leaderUnknown
			xcel.Leader = "unknown"
		} else {
			xcel.ServerResponse = leaderNotMe
			xcel.Leader = "http://" + xcelDB.xcelPeermap[leader]

		}
	}
	responseXML, _ := xml.Marshal(xcel)
	fmt.Fprintf(w, string(responseXML))

}
开发者ID:nilangshah,项目名称:XcelDB,代码行数:31,代码来源:XcelDB.go


示例7: TestChangesetMarshalXML

func TestChangesetMarshalXML(t *testing.T) {
	cs := Changeset{
		ID: 123,
	}

	data, err := xml.Marshal(cs)
	if err != nil {
		t.Fatalf("xml marshal error: %v", err)
	}

	expected := `<changeset id="123" user="" uid="0" created_at="0001-01-01T00:00:00Z" closed_at="0001-01-01T00:00:00Z" open="false" min_lat="0" max_lat="0" min_lon="0" max_lon="0"></changeset>`
	if !bytes.Equal(data, []byte(expected)) {
		t.Errorf("incorrect marshal, got: %s", string(data))
	}

	// changeset with discussion
	cs.Discussion = ChangesetDiscussion{
		Comments: []*ChangesetComment{
			&ChangesetComment{Text: "foo"},
		},
	}

	data, err = xml.Marshal(cs)
	if err != nil {
		t.Fatalf("xml marshal error: %v", err)
	}

	expected = `<changeset id="123" user="" uid="0" created_at="0001-01-01T00:00:00Z" closed_at="0001-01-01T00:00:00Z" open="false" min_lat="0" max_lat="0" min_lon="0" max_lon="0"><discussion><comment user="" uid="0" date="0001-01-01T00:00:00Z"><text>foo</text></comment></discussion></changeset>`
	if !bytes.Equal(data, []byte(expected)) {
		t.Errorf("incorrect marshal, got: %s", string(data))
	}
}
开发者ID:paulmach,项目名称:go.osm,代码行数:32,代码来源:changeset_test.go


示例8: closeSetup

// closeSetup does the same as closeError, except on a connection that has not finished stream setup.
func (s *Stream) closeSetup(c *Conn, err *Error) error {
	// Build response header
	reply := new(header)
	reply.Lang = "en"
	reply.Version = Version
	if len(s.config.Records) > 0 {
		reply.From = s.config.Records[0].Domain
	}

	if c.header != nil {
		if len(c.header.From) != 0 {
			recvFrom := JID{}
			recvFrom.Set(c.header.From)
			reply.To = recvFrom.String()
		}
		if len(c.header.To) != 0 {
			for _, record := range s.config.Records {
				if record.Domain == c.header.To {
					reply.From = c.header.To
					break
				}
			}
		}
		if len(c.header.Version) == 0 {
			reply.Version = ""
		} else if Version != c.header.Version {
			recvMajor, recvMinor := parseVersion(c.header.Version)
			thisMajor, thisMinor := parseVersion(Version)
			if recvMajor < thisMajor || (recvMajor == thisMajor && recvMinor < thisMinor) {
				reply.Version = c.header.Version
			}
		}
	}

	// Build tcp error packet
	xmlBytes := []byte(xml.Header)
	headerBytes, _ := xml.Marshal(reply)
	headerBytes = headerBytes[:len(headerBytes)-len("</stream>")]
	condBytes, _ := xml.Marshal(err)
	closeBytes := []byte("</stream>")

	errorPacket := bytes.Join([][]byte{xmlBytes, headerBytes, condBytes, closeBytes}, []byte{})

	c.Write(errorPacket)

	decoder := xml.NewDecoder(c)
	for {
		token, err := decoder.RawToken()
		if err != nil {
			break
		}
		if t, ok := token.(xml.EndElement); ok && t.Name.Local == "stream" {
			break
		}
	}

	return c.Close()
}
开发者ID:tuhuayuan,项目名称:go.xmpp,代码行数:59,代码来源:streams.go


示例9: ExampleSetUseNullEndTag

// This example demonstrates how SetUseNullEndTag changes the end tag syntax for Marshal.
func ExampleSetUseNullEndTag() {
	type NullValStruct struct {
		I int
		B []byte
		S string
	}
	s := new(NullValStruct)

	v, err := xml.Marshal(s)
	if err != nil {
		fmt.Println("err:", err.Error())
	} else {
		fmt.Println("s:", string(v))
	}

	xml.SetUseNullEndTag(true)
	v, err = xml.Marshal(s)
	if err != nil {
		fmt.Println("err:", err.Error())
	} else {
		fmt.Println("s:", string(v))
	}

	type NewStruct struct {
		NVS NullValStruct
		S   string
		F   float64
	}
	ss := new(NewStruct)

	v, err = xml.Marshal(ss)
	if err != nil {
		fmt.Println("err:", err.Error())
	} else {
		fmt.Println("ss:", string(v))
	}

	v, err = xml.MarshalIndent(ss, "  ", "   ")
	if err != nil {
		fmt.Println("err:", err.Error())
	} else {
		fmt.Println("ss indent:\n", string(v))
	}
	// Output:
	// s: <NullValStruct><I>0</I><B></B><S></S></NullValStruct>
	// s: <NullValStruct><I>0</I><B/><S/></NullValStruct>
	// ss: <NewStruct><NVS><I>0</I><B/><S/></NVS><S/><F>0</F></NewStruct>
	// ss indent:
	//    <NewStruct>
	//      <NVS>
	//         <I>0</I>
	//         <B/>
	//         <S/>
	//      </NVS>
	//      <S/>
	//      <F>0</F>
	//   </NewStruct>
}
开发者ID:govindarajan,项目名称:xml_hacked,代码行数:59,代码来源:example_test.go


示例10: TestVASTWithAds

func TestVASTWithAds(t *testing.T) {
	vast := VAST{Version: "2.0"}

	vast.Ad = append(vast.Ad, Ad{})
	data, err := xml.Marshal(vast)
	assert.Nil(t, err)
	assert.Equal(t, string(data), `<VAST version="2.0"><Ad id=""></Ad></VAST>`)

	vast.Ad = append(vast.Ad, Ad{})
	data, err = xml.Marshal(vast)
	assert.Nil(t, err)
	assert.Equal(t, string(data), `<VAST version="2.0"><Ad id=""></Ad><Ad id=""></Ad></VAST>`)
}
开发者ID:pubnative,项目名称:vast2-go,代码行数:13,代码来源:schema_test.go


示例11: putBucketRequest

// putBucketRequest wrapper creates a new putBucket request
func (a apiCore) putBucketRequest(bucket, acl, location string) (*request, error) {
	var r *request
	var err error
	op := &operation{
		HTTPServer: a.config.Endpoint,
		HTTPMethod: "PUT",
		HTTPPath:   separator + bucket,
	}
	var createBucketConfigBuffer *bytes.Reader
	// If location is set use it and create proper bucket configuration
	switch {
	case location != "":
		createBucketConfig := new(createBucketConfiguration)
		createBucketConfig.Location = location
		var createBucketConfigBytes []byte
		switch {
		case a.config.AcceptType == "application/xml":
			createBucketConfigBytes, err = xml.Marshal(createBucketConfig)
		case a.config.AcceptType == "application/json":
			createBucketConfigBytes, err = json.Marshal(createBucketConfig)
		default:
			createBucketConfigBytes, err = xml.Marshal(createBucketConfig)
		}
		if err != nil {
			return nil, err
		}
		createBucketConfigBuffer = bytes.NewReader(createBucketConfigBytes)
	}
	switch {
	case createBucketConfigBuffer == nil:
		r, err = newRequest(op, a.config, nil)
		if err != nil {
			return nil, err
		}
	default:
		r, err = newRequest(op, a.config, createBucketConfigBuffer)
		if err != nil {
			return nil, err
		}
		r.req.ContentLength = int64(createBucketConfigBuffer.Len())
	}
	// by default bucket is private
	switch {
	case acl != "":
		r.Set("x-amz-acl", acl)
	default:
		r.Set("x-amz-acl", "private")
	}

	return r, nil
}
开发者ID:dudymas,项目名称:mc,代码行数:52,代码来源:api-core.go


示例12: New

func New(code int, body interface{}, dataType string, ssl bool) (*httptest.Server, error) {

	if dataType == "xml" {

		_, err := xml.Marshal(body)

		if err != nil {
			return nil, err
		}

	} else if dataType == "json" {

		_, err := json.Marshal(body)

		if err != nil {
			return nil, err
		}

	} else {
		return nil, errors.New("dataType in MockServer not recognized")

	}

	f := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		var bodyMarshalled []byte

		if dataType == "xml" {
			w.Header().Set("Content-Type", "application/xml")
			bodyMarshalled, _ = xml.Marshal(body)

		} else if dataType == "json" {
			w.Header().Set("Content-Type", "application/json")
			bodyMarshalled, _ = json.Marshal(body)
		}

		w.WriteHeader(code)

		fmt.Fprintln(w, string(bodyMarshalled))
	})

	var server *httptest.Server

	if ssl {
		server = httptest.NewTLSServer(f)
	} else {
		server = httptest.NewServer(f)
	}

	return server, nil
}
开发者ID:Invoiced,项目名称:invoiced-go,代码行数:50,代码来源:invdmockserver.go


示例13: Marshal

func Marshal(resource interface{}, accept string, writer io.Writer, alt bool) (r *Error) {
	var err error
	var marshaller gocoding.Marshaller
	var renderer gocoding.Renderer

	if alt {
		marshaller = M.Alt
	} else {
		marshaller = M.Main
	}

	switch accept {
	case "text":
		renderer = json.RenderIndented(writer, "", "  ")

	case "json":
		renderer = json.Render(writer)

	case "xml":
		data, err := xml.Marshal(resource)
		if err != nil {
			r = CreateError(ErrorXMLMarshal, err.Error())
			data, err = xml.Marshal(r)
			if err != nil {
				panic(err)
			}
		}
		writer.Write(data)
		return

	case "html":
		renderer = html.Render(writer)

	default:
		resource = CreateError(ErrorUnsupportedMarshal, fmt.Sprintf(`"%s" is an unsupported marshalling format`, accept))
		renderer = json.Render(writer)
	}

	err = marshaller.Marshal(renderer, resource)
	if err != nil {
		r = CreateError(ErrorJSONMarshal, err.Error())
		err = marshaller.Marshal(renderer, r)
		if err != nil {
			panic(err)
		}
	}
	return
}
开发者ID:6londe,项目名称:FactomCode,代码行数:48,代码来源:marshal.go


示例14: Capture

func (c Client) Capture(cloudServiceName, deploymentName, roleName string,
	name, label string, osState OSState, parameters CaptureParameters) (management.OperationID, error) {
	if cloudServiceName == "" {
		return "", fmt.Errorf(errParamNotSpecified, "cloudServiceName")
	}
	if deploymentName == "" {
		return "", fmt.Errorf(errParamNotSpecified, "deploymentName")
	}
	if roleName == "" {
		return "", fmt.Errorf(errParamNotSpecified, "roleName")
	}

	request := CaptureRoleAsVMImageOperation{
		VMImageName:       name,
		VMImageLabel:      label,
		OSState:           osState,
		CaptureParameters: parameters,
	}
	data, err := xml.Marshal(request)
	if err != nil {
		return "", err
	}

	return c.SendAzurePostRequest(fmt.Sprintf(azureRoleOperationsURL,
		cloudServiceName, deploymentName, roleName), data)
}
开发者ID:forqlift,项目名称:azure-sdk-for-go,代码行数:26,代码来源:client.go


示例15: WriteAsXml

// WriteAsXml is a convenience method for writing a value in xml (requires Xml tags on the value)
func (r *Response) WriteAsXml(value interface{}) error {
	var output []byte
	var err error

	if value == nil { // do not write a nil representation
		return nil
	}
	if r.prettyPrint {
		output, err = xml.MarshalIndent(value, " ", " ")
	} else {
		output, err = xml.Marshal(value)
	}

	if err != nil {
		return r.WriteError(http.StatusInternalServerError, err)
	}
	r.Header().Set(HEADER_ContentType, MIME_XML)
	if r.statusCode > 0 { // a WriteHeader was intercepted
		r.ResponseWriter.WriteHeader(r.statusCode)
	}
	_, err = r.Write([]byte(xml.Header))
	if err != nil {
		return err
	}
	if _, err = r.Write(output); err != nil {
		return err
	}
	return nil
}
开发者ID:shenjinxi,项目名称:go-restful,代码行数:30,代码来源:response.go


示例16:

func (ø StringType) Xml() string {
	b, err := xl.Marshal(string(ø))
	if err != nil {
		panic("can't convert " + string(ø) + " to xml")
	}
	return string(b)
}
开发者ID:postfix,项目名称:typeconverter,代码行数:7,代码来源:string.go


示例17: WriteAsXml

func WriteAsXml(w http.ResponseWriter, status int, value interface{}, writeHeader bool, indent bool) (int, error) {
	var output []byte
	var err error

	if value == nil {
		return 0, nil
	}
	if indent {
		output, err = xml.MarshalIndent(value, " ", " ")
	} else {
		output, err = xml.Marshal(value)
	}

	if err != nil {
		return WriteString(w, http.StatusInternalServerError, err.Error())
	}
	w.Header().Set(constants.HEADER_ContentType, constants.MIME_XML)
	w.WriteHeader(status)
	if writeHeader {
		cl, err := w.Write([]byte(xml.Header))
		if err != nil {
			return cl, err
		}
	}
	return w.Write(output)

}
开发者ID:wlMalk,项目名称:gapi,代码行数:27,代码来源:functions.go


示例18: CreateStorageService

func CreateStorageService(name, location string) (*StorageService, error) {
	if len(name) == 0 {
		return nil, fmt.Errorf(azure.ParamNotSpecifiedError, "name")
	}
	if len(location) == 0 {
		return nil, fmt.Errorf(azure.ParamNotSpecifiedError, "location")
	}

	storageDeploymentConfig := createStorageServiceDeploymentConf(name, location)
	deploymentBytes, err := xml.Marshal(storageDeploymentConfig)
	if err != nil {
		return nil, err
	}

	requestId, err := azure.SendAzurePostRequest(azureStorageServiceListURL, deploymentBytes)
	if err != nil {
		return nil, err
	}

	azure.WaitAsyncOperation(requestId)
	storageService, err := GetStorageServiceByName(storageDeploymentConfig.ServiceName)
	if err != nil {
		return nil, err
	}

	return storageService, nil
}
开发者ID:MerlinDMC,项目名称:machine,代码行数:27,代码来源:storageServiceClient.go


示例19: FileSetXML

func FileSetXML(filename string, data interface{}) error {
	bytes, err := xml.Marshal(data)
	if err != nil {
		return err
	}
	return FileSetBytes(filename, bytes)
}
开发者ID:vincecima,项目名称:just-install,代码行数:7,代码来源:file.go


示例20: complete

func (w *writer) complete() error {

	b, err := xml.Marshal(w.xml)
	if err != nil {
		return err
	}

	uv := make(url.Values)
	uv.Set("uploadId", w.uploadId)

	url := w.o.url(`?` + uv.Encode())
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(b))
	if err != nil {
		return err
	}

	w.o.s3.signRequest(req)

	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if c := resp.StatusCode; c != 200 {
		return newS3Error(resp, "could not complete upload: %d", c)
	}
	return nil
}
开发者ID:ghp268,项目名称:s3,代码行数:29,代码来源:writer.go



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

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

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

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