示例#1
0
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)
}
示例#2
0
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)
}
示例#3
0
文件: server.go 项目: fsouza/go-iam
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,
		})
	}
}
示例#4
0
// 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
}
示例#5
0
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)
	}
}
示例#6
0
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
		}
	}
}
示例#7
0
// 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)
}
示例#8
0
文件: pcm.go 项目: cfstras/pcm
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")
}
示例#9
0
// 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())
		}
	}
}
示例#10
0
文件: headers.go 项目: kahing/minio
// 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()
}
示例#11
0
文件: badge.go 项目: zankard/drone
// 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)
}
示例#12
0
// 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
}
示例#13
0
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
}
示例#14
0
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
}
示例#15
0
// 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())
		}
	}
}
示例#16
0
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
}
示例#17
0
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
}
示例#18
0
文件: rss.go 项目: rpeer-denis/tcgl
// 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)
}
示例#19
0
文件: server.go 项目: jasonmoo/goamz
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)
		}
	}
}
示例#20
0
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
}
示例#21
0
func xmlWriter(w http.ResponseWriter, r *http.Request, d *responseRecord) {
	w.Header().Set("Content-Type", "application/xml")
	x := xml.NewEncoder(w)
	x.Indent("", "\t")
	x.Encode(d)
	w.Write([]byte{'\n'})
}
示例#22
0
func (v *xmlValue) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error {
	// The XML value of a property can be arbitrary, mixed-content XML.
	// To make sure that the unmarshalled value contains all required
	// namespaces, we encode all the property value XML tokens into a
	// buffer. This forces the encoder to redeclare any used namespaces.
	var b bytes.Buffer
	e := xml.NewEncoder(&b)
	for {
		t, err := next(d)
		if err != nil {
			return err
		}
		if e, ok := t.(xml.EndElement); ok && e.Name == start.Name {
			break
		}
		if err = e.EncodeToken(t); err != nil {
			return err
		}
	}
	err := e.Flush()
	if err != nil {
		return err
	}
	*v = b.Bytes()
	return nil
}
示例#23
0
func HandleNotFound(c context.Context, w http.ResponseWriter, e error) {
	w.WriteHeader(http.StatusNotFound)

	// Error can be nil.
	var errStr string
	if e != nil {
		errStr = e.Error()
		c.Infof("HandleNotFound: %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, NotFoundTpl, data)
	}
}
示例#24
0
// Receive structures on a channel, marshal them to XML, and send the
// bytes on a writer.
func (cl *Client) sendXml(w io.Writer, ch <-chan interface{}) {
	defer func(w io.Writer) {
		if c, ok := w.(io.Closer); ok {
			c.Close()
		}
	}(w)

	enc := xml.NewEncoder(w)

	for obj := range ch {
		if st, ok := obj.(*stream); ok {
			_, err := w.Write([]byte(st.String()))
			if err != nil {
				cl.setError(fmt.Errorf("send: %v", err))
				break
			}
		} else {
			err := enc.Encode(obj)
			if err != nil {
				cl.setError(fmt.Errorf("send: %v", err))
				break
			}
		}
	}
}
示例#25
0
func array2XlsxWriteSharedStrings(zw *zip.Writer, data [][]string) (err error) {
	siList := []xlsxSharedStringSi{{""}}
	for _, row := range data {
		for _, v1 := range row {
			if v1 == "" { //ignore blank cell can save space
				continue
			}
			siList = append(siList, xlsxSharedStringSi{v1})
		}
	}
	sst := xlsxSharedStringSst{
		Xmlns:  xmlNs,
		Count:  len(siList),
		SiList: siList,
	}
	thisW, err := zw.Create(sharedStringsFileName)
	_, err = thisW.Write([]byte(xml.Header))
	if err != nil {
		return
	}
	encoder := xml.NewEncoder(thisW)
	err = encoder.Encode(sst)
	if err != nil {
		return
	}
	return
}
示例#26
0
// Request implements the http.Handler interface to provide a drop-in Loginshare
// request/response handler
func (l *LoginShare) Request(w http.ResponseWriter, r *http.Request) {
	lsr, err := l.validateRequest(r)
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		log.Printf("invalid loginshare request from %s", r.RemoteAddr)
		return
	}

	if l.interfaceAllowed(lsr.Interface) == false {
		w.WriteHeader(http.StatusForbidden)
		log.Printf("loginshare request from %s for unpermitted interface", r.RemoteAddr)
		return
	}

	w.Header().Add("Content-Type", "application/xml")
	xw := xml.NewEncoder(w)
	resp, err := l.OnNewAuth(lsr)
	if err != nil {
		log.Printf("loginshare request from %s failed: %s", r.RemoteAddr, err)
		resp.StaffRecord = Staff{} // make sure we don't give up any info if partially populated
		resp.Result = 0
		resp.Message = err.Error()
		xw.Encode(resp)
		return
	}

	xw.Encode(resp)
	return
}
示例#27
0
文件: server.go 项目: fsouza/go-iam
func (srv *Server) error(w http.ResponseWriter, err *iam.Error) {
	w.WriteHeader(err.StatusCode)
	xmlErr := xmlErrors{Error: *err}
	if e := xml.NewEncoder(w).Encode(xmlErr); e != nil {
		panic(e)
	}
}
示例#28
0
func (t *XMLTransport) transport(
	e error,
	stack []*stackEntry,
	r *http.Request,
	context map[string]string,
	session map[string]interface{},
) error {
	xmln := t.newXMLNotice(e, stack, r, context, session)

	buf := bytes.NewBufferString(xml.Header)
	enc := xml.NewEncoder(buf)

	if err := enc.Encode(xmln); err != nil {
		return err
	}

	// Go currently ignores omitempty on CGIData.
	// b = bytes.Replace(b, []byte("<cgi-data></cgi-data>"), []byte{}, 1)

	resp, err := t.Client.Post(t.CreateAPIURL, "text/xml", buf)
	if err != nil {
		return err
	}
	resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf(
			"gobrake: got %v response, expected 200 OK", resp.StatusCode)
	}

	return nil
}
示例#29
0
文件: common.go 项目: GleasonK/go
// InitComplexMessage initializes a complex structure of the
// type CustomComplexMessage which includes a xml, struct of type PubnubDemoMessage,
// strings, float and integer.
func InitComplexMessage() CustomComplexMessage {
	pubnubDemoMessage := PubnubDemoMessage{
		DefaultMessage: "~!@#$%^&*()_+ `1234567890-= qwertyuiop[]\\ {}| asdfghjkl;' :\" zxcvbnm,./ <>? ",
	}

	xmlDoc := &Data{Name: "Doe", Age: 42}

	//_, err := xml.MarshalIndent(xmlDoc, "  ", "    ")
	//output, err := xml.MarshalIndent(xmlDoc, "  ", "    ")
	output := new(bytes.Buffer)
	enc := xml.NewEncoder(output)

	err := enc.Encode(xmlDoc)
	if err != nil {
		fmt.Printf("error: %v\n", err)
		return CustomComplexMessage{}
	}
	//fmt.Printf("xmlDoc: %v\n", xmlDoc)
	customComplexMessage := CustomComplexMessage{
		VersionID:     3.4,
		TimeToken:     13601488652764619,
		OperationName: "Publish",
		Channels:      []string{"ch1", "ch 2"},
		DemoMessage:   pubnubDemoMessage,
		//SampleXml        : xmlDoc,
		SampleXML: output.String(),
	}
	return customComplexMessage
}
示例#30
0
func (c *Client) NewRequest(method, url string, tracking bool, body interface{}) (*http.Request, error) {
	reqURL := url
	if !tracking {
		reqURL = path.Join(c.accountID, url)
	}

	reqURL = c.baseURL + reqURL

	buf := &bytes.Buffer{}
	if err := xml.NewEncoder(buf).Encode(&body); err != nil {
		return nil, err
	}
	req, err := http.NewRequest(method, reqURL, buf)
	if err != nil {
		return nil, err
	}

	if !tracking {
		req.Header.Add("Accept", "application/vnd.bpost.shm-order-v3.3+XML")
	}

	token := fmt.Sprintf("%s:%s", c.accountID, c.passPhrase)
	base64Str := encodeBase64([]byte(token))
	req.Header.Set("Authorization", "Basic "+base64Str)
	return req, nil
}