func TestOutAndBackIn(t *testing.T) { const ID = "/test1" ref := newRoute(ID) x, err := xml.MarshalIndent(ref, "", " ") if err != nil { t.Error(err) } /*t.Log("ref as xml is :", string(x))*/ var fresh Route //only empty fields err = xml.Unmarshal(x, &fresh) if err != nil { t.Error(err) } var x2 []byte x2, err = xml.MarshalIndent(fresh, "", " ") if err != nil { t.Error(err) } t.Log("fresh as xml is:", string(x2)) if string(x) != string(x2) { t.Error("not equal, sorry MAC") } }
func (c *Client) MakeRequest(otype, result string, updateCheck, isPing bool) (*omaha.Response, error) { client := &http.Client{} req := c.OmahaRequest(otype, result, updateCheck, isPing) raw, err := xml.MarshalIndent(req, "", " ") if err != nil { return nil, err } resp, err := client.Post(c.config.server+"/v1/update/", "text/xml", bytes.NewReader(raw)) if err != nil { return nil, err } defer resp.Body.Close() oresp := new(omaha.Response) err = xml.NewDecoder(resp.Body).Decode(oresp) if err != nil { return nil, err } if instanceFlags.verbose { raw, _ := xml.MarshalIndent(req, "", " ") c.Log("request: %s\n", string(raw)) raw, _ = xml.MarshalIndent(oresp, "", " ") c.Log("response: %s\n", string(raw)) } return oresp, nil }
func (cs *contentStore) processAtom(rawContent []byte, topic Topic) { atomFeed := &feeds.AtomFeed{} err := xml.Unmarshal(rawContent, atomFeed) if err != nil { log.Println("Couldn't parse atom content", err.Error()) return } items := cs.content[topic] if items == nil { cs.content[topic] = make(map[time.Time]string) items = cs.content[topic] } sortedDates := cs.contentSortedItems[topic] if sortedDates == nil { cs.contentSortedItems[topic] = make([]time.Time, 0, len(atomFeed.Entries)) sortedDates = cs.contentSortedItems[topic] } for _, newItem := range atomFeed.Entries { date, err := time.Parse(time.RFC3339, newItem.Updated) if err != nil { log.Printf("Couldn't parse %s as a RFC3339 date. Not accepting this.", newItem.Updated) continue } content, err := xml.MarshalIndent(newItem, "", " ") if err != nil { log.Println("Couldn't re-marshal element:", err.Error()) continue } sortedDates = insertDate(sortedDates, date) items[date] = string(content) } cs.contentSortedItems[topic] = sortedDates // since no one is supposed to use it afterwards ... atomFeed.Entries = []*feeds.AtomEntry{} header, err := xml.MarshalIndent(atomFeed, "", " ") if err != nil { log.Println("Error when re-marshaling header:", err.Error()) } cs.contentHeader[topic] = string(header) }
func (c *Client) openStreamAndGetFeatures() (*streamFeatures, error) { // Declare intent to be a xmpp client. openStream := fmt.Sprintf("<?xml version='1.0'?><stream:stream to='%s' xmlns='%s' xmlns:stream='%s' version='1.0'>", xmlEscape(c.domain), nsClient, nsStream) if Debug { fmt.Printf("===xmpp===send:\n%s\n", openStream) } fmt.Fprint(c.conn, openStream) // Server should respond with a stream opening. se, err := nextStart(c.p) if err != nil { return nil, err } if se.Name.Space != nsStream || se.Name.Local != "stream" { return nil, errors.New("xmpp: expected <stream> but got <" + se.Name.Local + "> in " + se.Name.Space) } features := &streamFeatures{} if err = c.p.DecodeElement(features, nil); err != nil { return nil, errors.New("unmarshal <features>: " + err.Error()) } if Debug { bytes, err := xml.MarshalIndent(features, "", " ") if err == nil { fmt.Printf("===xmpp===receive:%s\n", string(bytes)) } } return features, nil }
// 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 }
func (req DatasourceCreateRequest) XML() ([]byte, error) { tmp := struct { DatasourceCreateRequest XMLName struct{} `xml:"tsRequest"` }{DatasourceCreateRequest: req} return xml.MarshalIndent(tmp, "", " ") }
func (req QuerySiteResponse) XML() ([]byte, error) { tmp := struct { QuerySiteResponse XMLName struct{} `xml:"tsRequest"` }{QuerySiteResponse: req} return xml.MarshalIndent(tmp, "", " ") }
func (b *blankTarget) Convert(w io.Writer) error { var doc, err = xliffFromFile(b.inFile) if err != nil { return err } for i := range doc.File { doc.File[i].TargetLang = "" for j := range doc.File[i].Body.TransUnit { doc.File[i].Body.TransUnit[j].Target.Lang = "" doc.File[i].Body.TransUnit[j].Target.Inner = "" } } var out []byte if out, err = xml.MarshalIndent(doc, "", " "); err != nil { return err } io.WriteString(w, xml.Header) w.Write(out) return nil }
func createView(results []AvailabilityProfileOutput) ([]byte, error) { docRoot := &ReadRoot{} for _, row := range results { profile := &Profile{ ID: row.ID.Hex(), Name: row.Name, Namespace: row.Namespace, Poem: row.Poems[0], } and := &And{} docRoot.Profile = append(docRoot.Profile, profile) for _, group := range row.Groups { or := &Or{} for _, sf := range group { group := &Group{ ServiceFlavor: sf, } or.Group = append(or.Group, group) } and.Or = append(and.Or, or) } profile.And = and } output, err := xml.MarshalIndent(docRoot, " ", " ") return output, err }
func MarshalXmlToData(object interface{}) ([]byte, error) { if data, err := xml.MarshalIndent(object, "", " "); err != nil { return nil, err } else { return data, nil } }
func (*RssPlugin) Exec(topCtx mustache.Context) { title := FromCtx(topCtx, "site.title").(string) production_url := FromCtx(topCtx, "site.config.production_url").(string) pubDate := time.Now().Format("2006-01-02 03:04:05 +0800") post_ids := FromCtx(topCtx, "db.posts.chronological").([]string) posts := FromCtx(topCtx, "db.posts.dictionary").(map[string]Mapper) items := make([]RssItem, 0) for _, id := range post_ids { post := posts[id] item := RssItem{post.GetString("title"), production_url + post.Url(), post["_date"].(time.Time).Format("2006-01-02 03:04:05 +0800"), post["_content"].(*DocContent).Main} items = append(items, item) } rss := &Rss{"2.0", &RssChannel{title, production_url, pubDate, items}} f, err := os.OpenFile("compiled/rss.xml", os.O_CREATE|os.O_WRONLY, os.ModePerm) if err != nil { log.Println("ERR When Create RSS", err) return } defer f.Close() data, err := xml.MarshalIndent(rss, "", " ") if err != nil { log.Println("ERR When Create RSS", err) return } f.WriteString(`<?xml version="1.0"?>` + "\n" + `<rss version="2.0">`) f.Write(data[len(`<rss version="2.0">`)+1 : len(data)-len("</Rss>")]) f.WriteString("</rss>") f.Sync() return }
func (s *ReportDownloadService) Get(reportDefinition ReportDefinition) (res interface{}, err error) { reportDefinition.Selector.XMLName = xml.Name{baseUrl, "selector"} repDef := reportDefinitionXml{ ReportDefinition: &reportDefinition, XMLName: xml.Name{ Space: baseUrl, Local: "reportDefinition", }, } body, err := xml.MarshalIndent(repDef, " ", " ") if err != nil { return res, err } form := url.Values{} form.Add("__rdxml", string(body)) resp, err := s.makeRequest(form) if err != nil { return res, err } /*respBody, err := ioutil.ReadAll(resp.Body) if err != nil { return res, err } return string(respBody), err*/ return parseReport(resp.Body) }
func Test_AddAzureVMExtensionConfiguration(t *testing.T) { role := vm.Role{} AddAzureVMExtensionConfiguration(&role, "nameOfExtension", "nameOfPublisher", "versionOfExtension", "nameOfReference", "state", []byte{1, 2, 3}, []byte{}) data, err := xml.MarshalIndent(role, "", " ") if err != nil { t.Fatal(err) } if expected := `<Role> <ConfigurationSets></ConfigurationSets> <ResourceExtensionReferences> <ResourceExtensionReference> <ReferenceName>nameOfReference</ReferenceName> <Publisher>nameOfPublisher</Publisher> <Name>nameOfExtension</Name> <Version>versionOfExtension</Version> <ResourceExtensionParameterValues> <ResourceExtensionParameterValue> <Key>ignored</Key> <Value>AQID</Value> <Type>Public</Type> </ResourceExtensionParameterValue> </ResourceExtensionParameterValues> <State>state</State> </ResourceExtensionReference> </ResourceExtensionReferences> <DataVirtualHardDisks></DataVirtualHardDisks> </Role>`; string(data) != expected { t.Fatalf("Expected %q, but got %q", expected, string(data)) } }
//CreateXML encode into xml func (msg *GetParameterValuesResponse) CreateXML() []byte { env := Envelope{} id := IDStruct{"1", msg.GetID()} env.XmlnsEnv = "http://schemas.xmlsoap.org/soap/envelope/" env.XmlnsEnc = "http://schemas.xmlsoap.org/soap/encoding/" env.XmlnsXsd = "http://www.w3.org/2001/XMLSchema" env.XmlnsXsi = "http://www.w3.org/2001/XMLSchema-instance" env.XmlnsCwmp = "urn:dslforum-org:cwmp-1-0" env.Header = HeaderStruct{ID: id} paramLen := strconv.Itoa(len(msg.Values)) params := ParameterListStruct{Type: "cwmp:ParameterValueStruct[" + paramLen + "]"} for k, v := range msg.Values { param := ParameterValueStruct{ Name: NodeStruct{Type: XsdString, Value: k}, Value: NodeStruct{Type: XsdString, Value: v}} params.Params = append(params.Params, param) } info := getParameterValuesResponseStruct{Params: params} env.Body = getParameterValuesResponseBodyStruct{info} output, err := xml.MarshalIndent(env, " ", " ") //output, err := xml.Marshal(env) if err != nil { fmt.Printf("error: %v\n", err) } return output }
// XMLIndent sends an XML response with status code, but it applies prefix and indent to format the output. func (p Print) XMLIndent(code int, i interface{}, prefix string, indent string) (err error) { b, err := xml.MarshalIndent(i, prefix, indent) if err != nil { return err } return p.xml(code, b) }
func (stx3 *Stx3) Marshal() ([]byte, error) { result, err := xml.MarshalIndent(stx3, " ", " ") fullXml := xml.Header + string(result) return []byte(fullXml), err }
func (xe XmlEncoder) Encode(data interface{}) ([]byte, error) { if xe.PrettyPrint { return xml.MarshalIndent(data, "", " ") } else { return xml.Marshal(data) } }
func TestSerializeConfig(t *testing.T) { Convey("Serialize Config", t, func() { Convey("Serialize SCM", func() { scm := &Scm{ Class: "hudson.plugins.git.GitSCM", Plugin: "[email protected]", } b, e := xml.Marshal(scm) So(e, ShouldBeNil) if e != nil { So(e.Error(), ShouldEqual, "") } So(string(b), ShouldContainSubstring, `class="hudson.plugins.git.GitSCM`) }) Convey("Serialize Config", func() { config := &Config{} config.ShellBuilders = []*ShellBuilder{ {Command: "whoami"}, } b, e := xml.MarshalIndent(config, "", " ") So(e, ShouldBeNil) So(b, ShouldNotBeNil) t.Logf("%s", string(b)) }) }, ) }
func Encode(items []Item) ([]byte, error) { xmlitems := make([]item, len(items)) for i, item := range items { xmlitems[i].Item = item if item.Valid { xmlitems[i].XMLValid = "YES" } else { xmlitems[i].XMLValid = "NO" } if item.Icon.Type != "" { xmlitems[i].Icon = &item.Icon if xmlitems[i].Icon.Type == IconTypePath { xmlitems[i].Icon.Type = "" } } } bytes, err := xml.MarshalIndent(xmlitems, " ", " ") if err == nil { output := append([]byte(xml.Header), []byte("<items>\n")...) if bytes[0] == '\n' { bytes = bytes[1:] } output = append(output, bytes...) output = append(output, []byte("\n</items>\n")...) bytes = output } return bytes, err }
func (m *Master) outputAndroidFile() (string, error) { r, err := xml.MarshalIndent(m, "", " ") if err != nil { return "", err } return xml.Header + string(r), nil }
func (req SigninRequest) XML() ([]byte, error) { tmp := struct { SigninRequest XMLName struct{} `xml:"tsRequest"` }{SigninRequest: req} return xml.MarshalIndent(tmp, "", " ") }
func handlerSQLXML(w http.ResponseWriter, r *http.Request) { log.Println("Handling request from: ", r.RemoteAddr) users := []User{} err := DB.Select(&users, "select * from users") w.Header().Add("Content-Type", "text/xml; charset=UTF-8") if err != nil { log.Fatal(err) } fmt.Fprintf(w, "%s", "<Users>") for _, user := range users { val, err := xml.MarshalIndent(user, "", "\t") if err != nil { log.Fatal(err) } fmt.Fprintf(w, "%s\r\n\r\n", string(val)) } fmt.Fprintf(w, "%s", "</Users>") }
func (req CreateProjectRequest) XML() ([]byte, error) { tmp := struct { CreateProjectRequest XMLName struct{} `xml:"tsRequest"` }{CreateProjectRequest: req} return xml.MarshalIndent(tmp, "", " ") }
//CreateXML encode into xml func (msg *SetParameterValues) CreateXML() []byte { env := Envelope{} id := IDStruct{"1", msg.GetID()} env.XmlnsEnv = "http://schemas.xmlsoap.org/soap/envelope/" env.XmlnsEnc = "http://schemas.xmlsoap.org/soap/encoding/" env.XmlnsXsd = "http://www.w3.org/2001/XMLSchema" env.XmlnsXsi = "http://www.w3.org/2001/XMLSchema-instance" env.XmlnsCwmp = "urn:dslforum-org:cwmp-1-0" env.Header = HeaderStruct{ID: id, NoMore: msg.NoMore} paramLen := strconv.Itoa(len(msg.Params)) paramList := ParameterListStruct{Type: "cwmp:ParameterValueStruct[" + paramLen + "]"} for k, v := range msg.Params { param := ParameterValueStruct{ Name: NodeStruct{Value: k}, Value: NodeStruct{Type: v.Type, Value: v.Value}} paramList.Params = append(paramList.Params, param) } body := setParameterValuesStruct{ ParamList: paramList, ParameterKey: msg.ParameterKey, } env.Body = setParameterValuesBodyStruct{body} output, err := xml.MarshalIndent(env, " ", " ") //output, err := xml.Marshal(env) if err != nil { fmt.Printf("error: %v\n", err) } return output }
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) }
func Parse(r io.Reader) ([]byte, error) { p := h5.NewParser(r) err := p.Parse() if err != nil { return nil, err } tree := p.Tree() resp := Response() tree.Walk(func(n *h5.Node) { tag := n.Data() switch { case tag == "p": resp.Append(Say(n.Children[0].String())) case tag == "audio": for _, a := range n.Attr { if a.Name == "src" { resp.Append(Play(a.Value)) } } } }) return xml.MarshalIndent(resp, "", " ") }
//CreateXML encode xml func (msg *Download) CreateXML() []byte { env := Envelope{} env.XmlnsEnv = "http://schemas.xmlsoap.org/soap/envelope/" env.XmlnsEnc = "http://schemas.xmlsoap.org/soap/encoding/" env.XmlnsXsd = "http://www.w3.org/2001/XMLSchema" env.XmlnsXsi = "http://www.w3.org/2001/XMLSchema-instance" env.XmlnsCwmp = "urn:dslforum-org:cwmp-1-0" id := IDStruct{Attr: "1", Value: msg.GetID()} env.Header = HeaderStruct{ID: id, NoMore: msg.NoMore} body := downloadStruct{ CommandKey: msg.CommandKey, FileType: msg.FileType, URL: msg.URL, Username: msg.Username, Password: msg.Password, FileSize: msg.FileSize, TargetFileName: msg.TargetFileName, DelaySeconds: msg.DelaySeconds, SuccessURL: msg.SuccessURL, FailureURL: msg.FailureURL} env.Body = downloadBodyStruct{body} //output, err := xml.Marshal(env) output, err := xml.MarshalIndent(env, " ", " ") if err != nil { fmt.Printf("error: %v\n", err) } return output }
// 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) }
func showXml() { ctx := Configs{} err := xml.Unmarshal(buff, &ctx) if err != nil { fmt.Printf("unmarshal error: %v", err) return } fmt.Printf("Configs: %+v\n", ctx) // m, err := xml.MarshalIndent(ctx, "", "\t") if err != nil { fmt.Printf("marshal error: %v", err) return } fmt.Println() fmt.Println("same?", string(m) == string(buff)) fmt.Println() fmt.Println("strdatam:", string(m)) fmt.Println() fmt.Println("bytedatam:", m, "len:", len(m)) fmt.Println() fmt.Println("strdatab:", string(buff)) fmt.Println() fmt.Println("bytedatab:", buff, "len:", len(buff)) }
// Write writes the NFO into a writer func Write(w io.Writer, i interface{}) error { var nfo interface{} switch t := i.(type) { case *polochon.Movie: nfo = NewMovie(t) case *polochon.Show: nfo = NewShow(t) case *polochon.ShowEpisode: nfo = NewEpisode(t) default: return ErrInvalidType } b, err := xml.MarshalIndent(nfo, "", " ") if err != nil { return err } _, err = w.Write(b) if err != nil { return err } return nil }