本文整理汇总了Golang中encoding/xml.NewEncoder函数的典型用法代码示例。如果您正苦于以下问题:Golang NewEncoder函数的具体用法?Golang NewEncoder怎么用?Golang NewEncoder使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewEncoder函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: Export
func (this *manifest) Export(filepath string) error {
err := os.Remove(filepath)
if err != nil && !os.IsNotExist(err) {
return err
}
file, err := os.Create(filepath)
if err != nil {
return err
}
file.WriteString(manifestHeader)
encoder := xml.NewEncoder(file)
encoder.Indent("", " ")
err = encoder.Encode(this)
if err != nil {
return err
}
err = file.Close()
if err != nil {
return err
}
return nil
}
开发者ID:alexozer,项目名称:mesh-go,代码行数:27,代码来源:manifest.go
示例17: encodeRequestArgs
func encodeRequestArgs(w *bytes.Buffer, inAction interface{}) error {
in := reflect.Indirect(reflect.ValueOf(inAction))
if in.Kind() != reflect.Struct {
return fmt.Errorf("goupnp: SOAP inAction is not a struct but of type %v", in.Type())
}
enc := xml.NewEncoder(w)
nFields := in.NumField()
inType := in.Type()
for i := 0; i < nFields; i++ {
field := inType.Field(i)
argName := field.Name
if nameOverride := field.Tag.Get("soap"); nameOverride != "" {
argName = nameOverride
}
value := in.Field(i)
if value.Kind() != reflect.String {
return fmt.Errorf("goupnp: SOAP arg %q is not of type string, but of type %v", argName, value.Type())
}
if err := enc.EncodeElement(value.Interface(), xml.StartElement{xml.Name{"", argName}, nil}); err != nil {
return fmt.Errorf("goupnp: error encoding SOAP arg %q: %v", argName, err)
}
}
enc.Flush()
return nil
}
开发者ID:nilcons-contrib,项目名称:go-ethereum,代码行数:25,代码来源:soap.go
示例18: Encode
// Encode writes the RSS document to the writer.
func Encode(w io.Writer, rss *RSS) error {
enc := xml.NewEncoder(w)
if _, err := w.Write([]byte(xml.Header)); err != nil {
return err
}
return enc.Encode(rss)
}
开发者ID:rpeer-denis,项目名称:tcgl,代码行数:8,代码来源:rss.go
示例19: serveHTTP
func (srv *Server) serveHTTP(w http.ResponseWriter, req *http.Request) {
req.ParseForm()
srv.mutex.Lock()
defer srv.mutex.Unlock()
f := actions[req.Form.Get("Action")]
if f == nil {
srv.error(w, &elb.Error{
StatusCode: 400,
Code: "InvalidParameterValue",
Message: "Unrecognized Action",
})
}
reqId := fmt.Sprintf("req%0X", srv.reqId)
srv.reqId++
if resp, err := f(srv, w, req, reqId); err == nil {
if err := xml.NewEncoder(w).Encode(resp); err != nil {
panic(err)
}
} else {
switch err.(type) {
case *elb.Error:
srv.error(w, err.(*elb.Error))
default:
panic(err)
}
}
}
开发者ID:jasonmoo,项目名称:goamz,代码行数:27,代码来源:server.go
示例20: ChangeResourceRecordSets
func (client *Client) ChangeResourceRecordSets(hostedZone string, changes []*Change) error {
req := NewChangeResourceRecordSets(&ChangeBatch{
Changes: changes,
})
buf := &bytes.Buffer{}
e := xml.NewEncoder(buf).Encode(req)
if e != nil {
return e
}
httpRequest, e := http.NewRequest("POST", apiEndpoint+"/hostedzone/"+hostedZone+"/rrset", buf)
if e != nil {
return e
}
client.SignAwsRequest(httpRequest)
rsp, e := http.DefaultClient.Do(httpRequest)
if e != nil {
return e
}
defer rsp.Body.Close()
b, e := ioutil.ReadAll(rsp.Body)
if e != nil {
return e
}
if rsp.Status[0] != '2' {
return fmt.Errorf("expected status 2xx, got %s (%s)", rsp.Status, string(b))
}
return nil
}
开发者ID:himanshugpt,项目名称:evergreen,代码行数:31,代码来源:route53.go
注:本文中的encoding/xml.NewEncoder函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论