當前位置: 首頁>>代碼示例>>Golang>>正文


Golang xml.NewEncoder函數代碼示例

本文整理匯總了Golang中encoding/xml.NewEncoder函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewEncoder函數的具體用法?Golang NewEncoder怎麽用?Golang NewEncoder使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewEncoder函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: ServeAPI

func ServeAPI(w http.ResponseWriter, req *http.Request, g *git, ref string, maxCommits int) (err error) {
	// First, determine the encoding and error if it isn't appropriate
	// or supported. To do this, we need to check the api value and
	// Accept header. We also want to include the Content-Type.
	var e encoder
	var c string // The Content-Type field in the http.Response
	switch req.FormValue("api") {
	case "json":
		// The json.Encoder type implements our private encoder
		// interface, because it has the function Encode().
		c = "application/json"
		e = json.NewEncoder(w)
	case "xml":
		// Same as above.
		c = "application/xml"
		e = xml.NewEncoder(w)
	}
	// If the api field wasn't submitted in the form, we should still
	// check the Accept header.
	accept := strings.Split(strings.Split(
		req.Header.Get("Accept"), ";")[0],
		",")
	if e == nil && len(accept) != 0 {
		// Now we must loop through each element in accept, because
		// there can be multiple values to the Accept key. As soon as
		// we find an acceptable encoding, break the loop.
		for _, a := range accept {
			switch {
			case strings.HasSuffix(a, "/json"):
				e = json.NewEncoder(w)
			case strings.HasSuffix(a, "/xml"):
				e = xml.NewEncoder(w)
			}
			if e != nil {
				c = a // Set the content type appropriately.
				break
			}
		}
	}
	// If the encoding is invalid or not provided, return this error.
	if e == nil {
		return InvalidEncodingError
	}

	// If an encoding was provided, prepare a response.
	r := &APIResponse{
		GroveOwner:  gitVarUser(),
		HEAD:        g.SHA("HEAD"),
		Description: g.GetBranchDescription(ref),
		Commits:     g.Commits(ref, maxCommits),
	}
	// Set the Content-Type appropriately in the header.
	w.Header().Set("Content-Type", c)

	// Finally, encode to the http.ResponseWriter with whatever
	// encoder was selected.
	return e.Encode(r)
}
開發者ID:alexander-bauer,項目名稱:grove,代碼行數:58,代碼來源:api.go

示例2: Xml

func (r *Response) Xml(o interface{}) error {
	writeContentType(r.w, xmlContentType)
	if r.gzipOn {
		w := gzip.NewWriter(r.w)
		defer w.Close()
		defer w.Flush()
		err := xml.NewEncoder(w).Encode(o)
		return err
	}
	return xml.NewEncoder(r.w).Encode(o)
}
開發者ID:RoySusanoo,項目名稱:httpmux,代碼行數:11,代碼來源:response.go

示例3: serveHTTP

func (srv *Server) serveHTTP(w http.ResponseWriter, req *http.Request) {
	req.ParseForm()
	srv.mutex.Lock()
	defer srv.mutex.Unlock()
	action := req.FormValue("Action")
	if action == "" {
		srv.error(w, &iam.Error{
			StatusCode: 400,
			Code:       "MissingAction",
			Message:    "Missing action",
		})
	}
	if a, ok := actions[action]; ok {
		reqId := fmt.Sprintf("req%0X", srv.reqId)
		srv.reqId++
		if resp, err := a(srv, w, req, reqId); err == nil {
			if err := xml.NewEncoder(w).Encode(resp); err != nil {
				panic(err)
			}
		} else {
			switch err.(type) {
			case *iam.Error:
				srv.error(w, err.(*iam.Error))
			default:
				panic(err)
			}
		}
	} else {
		srv.error(w, &iam.Error{
			StatusCode: 400,
			Code:       "InvalidAction",
			Message:    "Invalid action: " + action,
		})
	}
}
開發者ID:fsouza,項目名稱:go-iam,代碼行數:35,代碼來源:server.go

示例4: Process

// Process executes the request to create a new report.
func (r *ICreateReq) Process() (*ICreateReqResp, error) {
	// log.Printf("%s\n", r)
	fail := func(err error) (*ICreateReqResp, error) {
		response := ICreateReqResp{
			Message:  "Failed",
			ID:       "",
			AuthorID: "",
		}
		return &response, err
	}

	var payload = new(bytes.Buffer)
	{
		enc := xml.NewEncoder(payload)
		enc.Indent("  ", "    ")
		enc.Encode(r)
	}
	// log.Printf("Payload:\n%v\n", payload.String())

	url := "http://localhost:5050/api/"
	resp, err := http.Post(url, "application/xml", payload)
	if err != nil {
		return fail(err)
	}

	var response ICreateReqResp
	err = xml.NewDecoder(resp.Body).Decode(&response)
	if err != nil {
		return fail(err)
	}

	return &response, nil
}
開發者ID:radhikapc,項目名稱:open311_gateway,代碼行數:34,代碼來源:create.go

示例5: HandleUnauthorized

func HandleUnauthorized(c context.Context, w http.ResponseWriter, e error) {
	w.WriteHeader(http.StatusUnauthorized)

	// Error can be nil.
	errStr := "You are not authorized to access this page."
	if e != nil {
		errStr = e.Error()
		c.Errorf("HandleUnauthorized: %v", errStr)
	}

	data := &errResult{
		Err: errStr,
		C:   c,
	}

	switch w.Header().Get("Content-Type") {
	case "application/json":
		if err := json.NewEncoder(w).Encode(data); err != nil {
			c.Errorf("json.Encode failed: %v", err)
			return
		}
	case "text/xml":
		w.Write([]byte(xml.Header))
		if err := xml.NewEncoder(w).Encode(data); err != nil {
			c.Errorf("xml.Encode failed: %v", err)
			return
		}
	default:
		HandleTemplate(c, w, UnauthorizedTpl, data)
	}
}
開發者ID:vmihailenco,項目名稱:appengine,代碼行數:31,代碼來源:httphelper.go

示例6: handleStatus

func handleStatus(c context.Context, w http.ResponseWriter, e error, status int) {
	w.WriteHeader(status)

	data := &errResult{
		C:   c,
		Err: e.Error(),
	}
	switch w.Header().Get("Content-Type") {
	case "application/json":
		if err := json.NewEncoder(w).Encode(data); err != nil {
			c.Errorf("json.Encode failed: %v", err)
			return
		}
	case "text/xml":
		w.Write([]byte(xml.Header))
		if err := xml.NewEncoder(w).Encode(data); err != nil {
			c.Errorf("xml.Encode failed: %v", err)
			return
		}
	default:
		if err := ErrorTpl.Execute(w, data); err != nil {
			c.Errorf("errLayout.Execute failed: %v", err)
			return
		}
	}
}
開發者ID:vmihailenco,項目名稱:appengine,代碼行數:26,代碼來源:httphelper.go

示例7: writeXML

// writeXML marshalls the value to JSON and set the Content-Type Header.
func writeXML(resp *Response, status int, contentType string, v interface{}) error {
	if v == nil {
		resp.WriteHeader(status)
		// do not write a nil representation
		return nil
	}
	if resp.prettyPrint {
		// pretty output must be created and written explicitly
		output, err := xml.MarshalIndent(v, " ", " ")
		if err != nil {
			return err
		}
		resp.Header().Set(HEADER_ContentType, contentType)
		resp.WriteHeader(status)
		_, err = resp.Write([]byte(xml.Header))
		if err != nil {
			return err
		}
		_, err = resp.Write(output)
		return err
	}
	// not-so-pretty
	resp.Header().Set(HEADER_ContentType, contentType)
	resp.WriteHeader(status)
	return xml.NewEncoder(resp).Encode(v)
}
開發者ID:40a,項目名稱:bootkube,代碼行數:27,代碼來源:entity_accessors.go

示例8: saveConns

func saveConns(conf *types.Configuration) {
	filename := replaceHome(connectionsPath)
	tmp := filename + ".tmp"
	wr, err := os.Create(tmp)
	p(err, "opening "+filename)
	defer func() {
		if err := os.Rename(tmp, filename); err != nil {
			p(os.Remove(filename), "deleting old connections.xml")
			p(os.Rename(tmp, filename), "overwriting connections.xml")
		}
	}()
	defer wr.Close()

	encoding := unicode.UTF16(unicode.LittleEndian, unicode.ExpectBOM)
	textEncoder := encoding.NewEncoder()

	writer := textEncoder.Writer(wr)
	fmt.Fprintln(writer, `<?xml version="1.0" encoding="utf-16"?>
<!-- ****************************************************************-->
<!-- *                                                              *-->
<!-- * PuTTY Configuration Manager save file - All right reserved.  *-->
<!-- *                                                              *-->
<!-- ****************************************************************-->
<!-- The following lines can be modified at your own risks.  -->`)

	encoder := xml.NewEncoder(writer)
	encoder.Indent("", "  ")
	p(encoder.Encode(&conf), "encoding xml")
}
開發者ID:cfstras,項目名稱:pcm,代碼行數:29,代碼來源:pcm.go

示例9: TestBilling_Encoding

// TestBillingEncoding ensures structs are encoded to XML properly.
// Because Recurly supports partial updates, it's important that only defined
// fields are handled properly -- including types like booleans and integers which
// have zero values that we want to send.
func TestBilling_Encoding(t *testing.T) {
	tests := []struct {
		v        Billing
		expected string
	}{
		{v: Billing{}, expected: "<billing_info></billing_info>"},
		{v: Billing{Token: "507c7f79bcf86cd7994f6c0e"}, expected: "<billing_info><token_id>507c7f79bcf86cd7994f6c0e</token_id></billing_info>"},
		{v: Billing{FirstName: "Verena", LastName: "Example"}, expected: "<billing_info><first_name>Verena</first_name><last_name>Example</last_name></billing_info>"},
		{v: Billing{Address: "123 Main St."}, expected: "<billing_info><address1>123 Main St.</address1></billing_info>"},
		{v: Billing{Address2: "Unit A"}, expected: "<billing_info><address2>Unit A</address2></billing_info>"},
		{v: Billing{City: "San Francisco"}, expected: "<billing_info><city>San Francisco</city></billing_info>"},
		{v: Billing{State: "CA"}, expected: "<billing_info><state>CA</state></billing_info>"},
		{v: Billing{Zip: "94105"}, expected: "<billing_info><zip>94105</zip></billing_info>"},
		{v: Billing{Country: "US"}, expected: "<billing_info><country>US</country></billing_info>"},
		{v: Billing{Phone: "555-555-5555"}, expected: "<billing_info><phone>555-555-5555</phone></billing_info>"},
		{v: Billing{VATNumber: "abc"}, expected: "<billing_info><vat_number>abc</vat_number></billing_info>"},
		{v: Billing{IPAddress: net.ParseIP("127.0.0.1")}, expected: "<billing_info><ip_address>127.0.0.1</ip_address></billing_info>"},
		{v: Billing{Number: 4111111111111111, Month: 5, Year: 2020, VerificationValue: 111}, expected: "<billing_info><number>4111111111111111</number><month>5</month><year>2020</year><verification_value>111</verification_value></billing_info>"},
		{v: Billing{RoutingNumber: "065400137", AccountNumber: "0123456789", AccountType: "checking"}, expected: "<billing_info><routing_number>065400137</routing_number><account_number>0123456789</account_number><account_type>checking</account_type></billing_info>"},
	}

	for _, tt := range tests {
		var buf bytes.Buffer
		if err := xml.NewEncoder(&buf).Encode(tt.v); err != nil {
			t.Fatalf("unexpected error: %v", err)
		} else if buf.String() != tt.expected {
			t.Fatalf("unexpected value: %s", buf.String())
		}
	}
}
開發者ID:blacklightcms,項目名稱:go-recurly,代碼行數:34,代碼來源:billing_test.go

示例10: encodeErrorResponse

// Write error response headers
func encodeErrorResponse(response interface{}, acceptsType contentType) []byte {
	var bytesBuffer bytes.Buffer
	var e encoder
	// write common headers
	switch acceptsType {
	case xmlContentType:
		e = xml.NewEncoder(&bytesBuffer)
	case jsonContentType:
		e = json.NewEncoder(&bytesBuffer)
	// by default even if unknown Accept header received handle it by sending XML contenttype response
	default:
		e = xml.NewEncoder(&bytesBuffer)
	}
	e.Encode(response)
	return bytesBuffer.Bytes()
}
開發者ID:kahing,項目名稱:minio,代碼行數:17,代碼來源:headers.go

示例11: GetCC

// GetCC accepts a request to retrieve the latest build
// status for the given repository from the datastore and
// in CCTray XML format.
//
//     GET /api/badge/:host/:owner/:name/cc.xml
//
func GetCC(c web.C, w http.ResponseWriter, r *http.Request) {
	var ctx = context.FromC(c)
	var (
		host  = c.URLParams["host"]
		owner = c.URLParams["owner"]
		name  = c.URLParams["name"]
	)

	w.Header().Set("Content-Type", "application/xml")

	repo, err := datastore.GetRepoName(ctx, host, owner, name)
	if err != nil {
		w.WriteHeader(http.StatusNotFound)
		return
	}
	commits, err := datastore.GetCommitList(ctx, repo, 1, 0)
	if err != nil || len(commits) == 0 {
		w.WriteHeader(http.StatusNotFound)
		return
	}

	var link = httputil.GetURL(r) + "/" + repo.Host + "/" + repo.Owner + "/" + repo.Name
	var cc = model.NewCC(repo, commits[0], link)
	xml.NewEncoder(w).Encode(cc)
}
開發者ID:zankard,項目名稱:drone,代碼行數:31,代碼來源:badge.go

示例12: SendIQ

// SendIQ sends an info/query message to the given user. It returns a channel
// on which the reply can be read when received and a Cookie that can be used
// to cancel the request.
func (c *Conn) SendIQ(to, typ string, value interface{}) (reply chan Stanza, cookie Cookie, err error) {
	c.lock.Lock()
	defer c.lock.Unlock()

	cookie = c.getCookie()
	reply = make(chan Stanza, 1)

	toAttr := ""
	if len(to) > 0 {
		toAttr = "to='" + xmlEscape(to) + "'"
	}
	if _, err = fmt.Fprintf(c.out, "<iq %s from='%s' type='%s' id='%d'>", toAttr, xmlEscape(c.jid), xmlEscape(typ), cookie); err != nil {
		return
	}
	if _, ok := value.(EmptyReply); !ok {
		if err = xml.NewEncoder(c.out).Encode(value); err != nil {
			return
		}
	}
	if _, err = fmt.Fprintf(c.out, "</iq>"); err != nil {
		return
	}

	c.inflights[cookie] = reply
	return
}
開發者ID:dotdotdotpaul,項目名稱:xmpp,代碼行數:29,代碼來源:xmpp.go

示例13: handleMultiCall

func handleMultiCall(w http.ResponseWriter, r *http.Request, params []value) bool {
	if got, want := len(params), 1; got != want {
		log.Fatalf("system.multicall has wrong number of parameters: got %d, want %d", got, want)
	}
	calls := params[0].Array
	for _, subcall := range calls {
		// Each subcall has a struct with methodName and params as members.
		if got, want := len(subcall.Struct), 2; got != want {
			log.Fatalf("system.multicall call has wrong number of struct members: got %d, want %d", got, want)
		}
		if got, want := subcall.Struct[0].Name, "methodName"; got != want {
			log.Fatalf("system.multicall struct member has wrong name: got %s, want %s", got, want)
		}
		if got, want := subcall.Struct[1].Name, "params"; got != want {
			log.Fatalf("system.multicall struct member has wrong name: got %s, want %s", got, want)
		}
		methodName := subcall.Struct[0].Value.InnerXML
		params := subcall.Struct[1].Value.Array
		dispatch(w, r, methodName, params)
	}
	startXMLReply(w)
	xml.NewEncoder(w).Encode(&(struct {
		XMLName xml.Name `xml:"methodResponse"`
		Methods []value  `xml:"params>param>value>array>data>value"`
	}{}))
	return true
}
開發者ID:stapelberg,項目名稱:zkj-nas-tools,代碼行數:27,代碼來源:hm2prometheus.go

示例14: Transcode

func Transcode(r io.Reader, w io.Writer) error {
	gpfeed, err := ReadGPFeed(r)
	if err != nil {
		return err
	}

	now := time.Now()
	atomfeed := AtomFeed{
		Title:   gpfeed.Title,
		Id:      gpfeed.Id,
		XMLNS:   "http://www.w3.org/2005/Atom",
		Updated: now.In(time.UTC).Format("2006-01-02T15:04:05Z"),
	}
	for _, item := range gpfeed.Items {
		link := AtomLink{
			Href: item.Object.Url,
		}
		entry := AtomEntry{
			Title:     item.Title,
			Id:        "tag:google.com,1970:" + item.Id,
			Author:    AtomAuthor{Name: item.Actor.DisplayName},
			Updated:   item.Updated,
			Published: item.Published,
			Summary:   AtomText{Type: "html", Text: RenderPost(item)},
			Link:      []*AtomLink{&link},
		}
		atomfeed.Entry = append(atomfeed.Entry, &entry)
	}
	if err := xml.NewEncoder(w).Encode(&atomfeed); err != nil {
		return err
	}
	return nil
}
開發者ID:evmar,項目名稱:evanhacks,代碼行數:33,代碼來源:transcode.go

示例15: TestPlans_Encoding

// TestPlansEncoding ensures structs are encoded to XML properly.
// Because Recurly supports partial updates, it's important that only defined
// fields are handled properly -- including types like booleans and integers which
// have zero values that we want to send.
func TestPlans_Encoding(t *testing.T) {
	tests := []struct {
		v        Plan
		expected string
	}{
		// name is a required field. It should always be present.
		{v: Plan{}, expected: "<plan><name></name></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, Description: "abc"}, expected: "<plan><name>Gold plan</name><description>abc</description><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, AccountingCode: "gold"}, expected: "<plan><name>Gold plan</name><accounting_code>gold</accounting_code><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, IntervalUnit: "months"}, expected: "<plan><name>Gold plan</name><plan_interval_unit>months</plan_interval_unit><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, IntervalLength: 1}, expected: "<plan><name>Gold plan</name><plan_interval_length>1</plan_interval_length><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, TrialIntervalUnit: "days"}, expected: "<plan><name>Gold plan</name><trial_interval_unit>days</trial_interval_unit><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, TrialIntervalLength: 10}, expected: "<plan><name>Gold plan</name><trial_interval_length>10</trial_interval_length><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, IntervalUnit: "months"}, expected: "<plan><name>Gold plan</name><plan_interval_unit>months</plan_interval_unit><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, SetupFeeInCents: UnitAmount{USD: 1000, EUR: 800}}, expected: "<plan><name>Gold plan</name><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents><setup_fee_in_cents><USD>1000</USD><EUR>800</EUR></setup_fee_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, TotalBillingCycles: NewInt(24)}, expected: "<plan><name>Gold plan</name><total_billing_cycles>24</total_billing_cycles><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, UnitName: "unit"}, expected: "<plan><name>Gold plan</name><unit_name>unit</unit_name><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, DisplayQuantity: NewBool(true)}, expected: "<plan><name>Gold plan</name><display_quantity>true</display_quantity><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, DisplayQuantity: NewBool(false)}, expected: "<plan><name>Gold plan</name><display_quantity>false</display_quantity><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, SuccessURL: "https://example.com/success"}, expected: "<plan><name>Gold plan</name><success_url>https://example.com/success</success_url><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, CancelURL: "https://example.com/cancel"}, expected: "<plan><name>Gold plan</name><cancel_url>https://example.com/cancel</cancel_url><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, TaxExempt: NewBool(true)}, expected: "<plan><name>Gold plan</name><tax_exempt>true</tax_exempt><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, TaxExempt: NewBool(false)}, expected: "<plan><name>Gold plan</name><tax_exempt>false</tax_exempt><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
		{v: Plan{Name: "Gold plan", UnitAmountInCents: UnitAmount{USD: 1500}, TaxCode: "physical"}, expected: "<plan><name>Gold plan</name><tax_code>physical</tax_code><unit_amount_in_cents><USD>1500</USD></unit_amount_in_cents></plan>"},
	}

	for _, tt := range tests {
		var buf bytes.Buffer
		if err := xml.NewEncoder(&buf).Encode(tt.v); err != nil {
			t.Fatalf("TestPlansEncoding Error: %s", err)
		} else if buf.String() != tt.expected {
			t.Fatalf("unexpected encoding: %s", buf.String())
		}
	}
}
開發者ID:blacklightcms,項目名稱:go-recurly,代碼行數:39,代碼來源:plans_test.go


注:本文中的encoding/xml.NewEncoder函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。