func DecodeClientToClientMessage(msg []byte) (Type, *UserToUserPackage, error) { var m ClientToClientMessage err := xml.Unmarshal(msg, &m) if err != nil { return UNKNOWN_T, nil, err } switch m.Type { case VOTE: var v VoteMessage err := xml.Unmarshal(msg, &v) if err != nil { return UNKNOWN_T, nil, errors.New("Couldn't decode the message: Broadcast or direct message malformed") } uu := UserToUserPackage{ VoteMessage: &v, } return VOTE_T, &uu, nil case COORDINATOR: var v CoordinatorMessage err := xml.Unmarshal(msg, &v) if err != nil { return UNKNOWN_T, nil, errors.New("Couldn't decode the message: Broadcast or direct message malformed") } uu := UserToUserPackage{ CoordinatorMessage: &v, } return COORDINATOR_T, &uu, nil } return UNKNOWN_T, nil, errors.New("Couldn't decode the message: No matching type") }
func RegisterDevice(token string, customData string, userId string, userSecret string, region string, applicationArn string) (arn string, err error) { values := url.Values{} values.Set("Action", "CreatePlatformEndpoint") values.Set("CustomUserData", customData) values.Set("Token", token) values.Set("PlatformApplicationArn", applicationArn) values.Set("Timestamp", time.Now().UTC().Format(time.RFC3339)) response, err := makeRequest("http://sns."+region+".amazonaws.com/", values, userId, userSecret, region) if err != nil { return "", err } defer response.Body.Close() if response.StatusCode != 200 { content, _ := ioutil.ReadAll(response.Body) var errorResponse aws.ErrorResponse xml.Unmarshal(content, &errorResponse) return "", errors.New("Unable to register device. " + errorResponse.Error.Code + ": " + errorResponse.Error.Message) } else { content, _ := ioutil.ReadAll(response.Body) var createResponse CreateResponse xml.Unmarshal(content, &createResponse) return createResponse.CreatePlatformEndpointResult.EndpointArn, nil } }
func (client *Client) loadCloudFormationResource(action string, params Values, i interface{}) error { req, e := client.signedCloudFormationRequest(action, params) rsp, e := httpClient.Do(req) if e != nil { return e } defer rsp.Body.Close() b, e := ioutil.ReadAll(rsp.Body) if e != nil { return e } switch rsp.StatusCode { case 404: return ErrorNotFound case 200: if i != nil { return xml.Unmarshal(b, i) } return nil default: ersp := &ErrorResponse{} dbg.Printf("ERROR=%q", string(b)) e = xml.Unmarshal(b, ersp) if e != nil { return fmt.Errorf("expected status 2xx but got %s (%s)", rsp.Status, string(b)) } if strings.Contains(ersp.Error.Message, "does not exist") { return ErrorNotFound } return fmt.Errorf(ersp.Error.Message) } }
//解析配置文件内容至内存中 func Analyse() error { content, err := ioutil.ReadFile("../etc/config.xml") if err != nil { Log.Error(err) return err } err = xml.Unmarshal(content, &config) if err != nil { Log.Error(err) return err } content, err = ioutil.ReadFile("../etc/entity.xml") err = xml.Unmarshal(content, &entitys) if err != nil { Log.Error(err) return err } content, err = ioutil.ReadFile("../etc/url.xml") err = xml.Unmarshal(content, &urls) if err != nil { Log.Error(err) return err } return nil }
func WexinHandler(resp http.ResponseWriter, req *http.Request) { log.Println("method:", req.Method) if req.Method == "GET" { weixinValid(resp, req) } else { data, err := ioutil.ReadAll(req.Body) if nil != err { log.Println("read body err:", err) return } log.Println("data:", string(data)) request := &entry.ReqMessage{} er := xml.Unmarshal(data, request) if nil != er { log.Println("decode body err:", er) return } event := request.Event msgType := request.MsgType ch := make(chan interface{}) defer close(ch) if "event" == msgType && event == "subscribe" { //添加关注事件 go subEventProcess(*request, ch) } else if "event" == msgType && event == "unsubscribe" { //取消订阅 go unsubEventProcess(*request, ch) } else if "location" == msgType { //地理位置 var msg entry.LocRequest err := xml.Unmarshal(data, &msg) if nil != err { log.Println("decode txt request body err:", err) return } go locMessageProcess(msg, ch) } else { var msg entry.TxtRequest err := xml.Unmarshal(data, &msg) if nil != err { log.Println("decode txt request body err:", er) return } go txtMessageProcess(msg, ch) } brespons, _ := xml.Marshal(<-ch) log.Println(string(brespons)) resp.Write(brespons) } }
func (c *AliOSSClient) GetLocationOfBucket(bucket string) (string, error) { uri := fmt.Sprintf("/%s/?location", bucket) query := make(map[string]string) query["location"] = "" s := &oss_agent{ AccessKey: c.AccessKey, AccessKeySecret: c.AccessKeySecret, Verb: "GET", Url: fmt.Sprintf("http://%s.%s", bucket, c.EndPoint), CanonicalizedHeaders: make(map[string]string), CanonicalizedUri: uri, CanonicalizedQuery: query, Content: &bytes.Reader{}, ContentType: "", Debug: c.Debug, logger: c.logger, } v := "" e := &AliOssError{} resp, xml_result, err := s.send_request(false) if err != nil { return "", err } if resp.StatusCode == 200 { xml.Unmarshal(xml_result, &v) return v, nil } else { xml.Unmarshal(xml_result, e) return "", e } }
func callRet(ret interface{}, resp *http.Response) (code int, err error) { var ( b []byte er errRet ) code = resp.StatusCode if code/100 == 2 { if ret == nil || resp.ContentLength == 0 { return } b, err = ioutil.ReadAll(resp.Body) if err != nil { return } ct := resp.Header.Get("Content-Type") if strings.Contains(ct, "application/json") { err = json.Unmarshal(b, ret) } else { // default decoding err = xml.Unmarshal(b, ret) } } else { if resp.ContentLength == 0 { return } b, err = ioutil.ReadAll(resp.Body) if err != nil { return } if err = xml.Unmarshal(b, &er); err != nil { return } err = errors.New(er.Code) } return }
func main() { data, err := ioutil.ReadFile("page.xml") if nil != err { fmt.Println(err) } { v := new(BlogContainer) err = xml.Unmarshal(data, v) if nil != err { fmt.Println(err) return } fmt.Printf("XMLName: %#v\n", v.XMLName) fmt.Printf("XMLName: %#v\n", v.Chapter.XMLName) fmt.Printf("Title: %v\n", v.Chapter.Title) for i, x := range v.Chapter.Name { fmt.Printf("Chapter %d: %v\n", i, x) } } { v := new(Blog) err = xml.Unmarshal(data, v) if nil != err { fmt.Println(err) return } fmt.Println(v.Title) fmt.Println(v.Tags) fmt.Println(v.Chapters) } }
func (r *Request) cachingReadEntity(contentType string, entityPointer interface{}) (err error) { var buffer []byte if r.bodyContent != nil { buffer = *r.bodyContent } else { buffer, err = ioutil.ReadAll(r.Request.Body) if err != nil { return err } r.bodyContent = &buffer } if strings.Contains(contentType, MIME_XML) { return xml.Unmarshal(buffer, entityPointer) } if strings.Contains(contentType, MIME_JSON) { return json.Unmarshal(buffer, entityPointer) } if MIME_XML == defaultRequestContentType { return xml.Unmarshal(buffer, entityPointer) } if MIME_JSON == defaultRequestContentType { return json.Unmarshal(buffer, entityPointer) } return NewError(400, "Unable to unmarshal content of type:"+contentType) }
func ReadCommandsFile(basedir string) (*CommandsXML, error) { commandsdata, err := ioutil.ReadFile(filepath.Join(basedir, "doc", "commands-xml", "commands.xml")) if err != nil { return nil, err } cs := &CommandsXMLSimple{} err = xml.Unmarshal(commandsdata, cs) if err != nil { return nil, err } c := &CommandsXML{} c.de = make(map[string]CommandsxmlCommand) c.en = make(map[string]CommandsxmlCommand) commandTranslationsEnDe = make(map[string]string) for _, v := range cs.Commands { commandTranslationsEnDe[v.En] = v.De } err = xml.Unmarshal(commandsdata, c) if err != nil { return nil, err } for _, v := range c.Commands { c.de[v.De] = v c.en[v.En] = v } return c, err }
func ParseFileList(in io.Reader, out *FileListing) (err error) { defer func() { out.Name = out.Base }() data, err := ioutil.ReadAll(in) if err != nil { return } /* First, try just reading it */ err = xml.Unmarshal(data, out) if err == nil { return } /* If that failed, then try to read in another charset. This happens because * microdc2 is known to lie by saying that the content is utf-8 when it's * actually iso-8859-1 */ translator, err := charset.TranslatorFrom("iso-8859-1") if err != nil { return } _, data, err = translator.Translate(data, true) if err != nil { return } return xml.Unmarshal(data, out) }
//get cores rule func (c *AliOSSClient) GetCoreRule(bucket string) (*CORSConfiguration, error) { uri := fmt.Sprintf("/%s/?cors", bucket) query := make(map[string]string) header := make(map[string]string) query["cors"] = "" s := &oss_agent{ AccessKey: c.AccessKey, AccessKeySecret: c.AccessKeySecret, Verb: "GET", Url: fmt.Sprintf("http://%s.%s", bucket, c.EndPoint), CanonicalizedHeaders: header, CanonicalizedUri: uri, CanonicalizedQuery: query, Content: &bytes.Reader{}, Debug: c.Debug, logger: c.logger, } v := &CORSConfiguration{} e := &AliOssError{} resp, xml_result, err := s.send_request(false) if err != nil { return nil, err } if resp.StatusCode/100 == 2 { xml.Unmarshal(xml_result, v) return v, nil } else { xml.Unmarshal(xml_result, e) return nil, e } }
//Init multipart upload func (c *AliOSSClient) GetInitMultipartUpload(bucket string, key string) (*MultiUploadInit, error) { uri := fmt.Sprintf("/%s/%s?uploads", bucket, key) query := make(map[string]string) header := make(map[string]string) query["uploads"] = "" s := &oss_agent{ AccessKey: c.AccessKey, AccessKeySecret: c.AccessKeySecret, Verb: "POST", Url: fmt.Sprintf("http://%s.%s/%s", bucket, c.EndPoint, key), CanonicalizedHeaders: header, CanonicalizedUri: uri, CanonicalizedQuery: query, Content: &bytes.Reader{}, Debug: c.Debug, logger: c.logger, } v := &MultiUploadInit{} e := &AliOssError{} resp, xml_result, err := s.send_request(false) if err != nil { return nil, err } if resp.StatusCode/100 == 2 { xml.Unmarshal(xml_result, v) return v, nil } else { xml.Unmarshal(xml_result, e) return nil, e } }
func main() { f, err := ioutil.ReadFile("example.xml") check(err) a := new(lib.Spells) err = xml.Unmarshal(f, &a) check(err) fmt.Printf("%+v", a) fmt.Println(" ") result, err := json.MarshalIndent(a, "", " ") check(err) fmt.Printf("%+v", string(result)) data := []byte("<cells><cell><name>Thomas</name></cell><cell><name>Janes</name></cell></cells>") b := new(Cells) err = xml.Unmarshal(data, &b) check(err) fmt.Printf("%+v", b) dataJson, err := json.MarshalIndent(b, "", " ") check(err) fmt.Println(string(dataJson)) c := new(TmpJson) err = json.Unmarshal(dataJson, &c) check(err) fmt.Printf("\n\n%+v", c) }
func (c *AliOSSClient) CloseBucketLogging(name string) error { xml_content := `<?xml version="1.0" encoding="UTF-8"?><BucketLoggingStatus></BucketLoggingStatus>` uri := fmt.Sprintf("/%s/?logging", name) query := make(map[string]string) header := make(map[string]string) query["logging"] = "" s := &oss_agent{ AccessKey: c.AccessKey, AccessKeySecret: c.AccessKeySecret, Verb: "PUT", Url: fmt.Sprintf("http://%s.%s", name, c.EndPoint), CanonicalizedHeaders: header, CanonicalizedUri: uri, CanonicalizedQuery: query, Content: bytes.NewReader([]byte(xml_content)), ContentType: "application/xml", Debug: c.Debug, logger: c.logger, } v := &BucketList{} e := &AliOssError{} resp, xml_result, err := s.send_request(false) if err != nil { return err } if resp.StatusCode/100 == 2 { xml.Unmarshal(xml_result, v) return nil } else { xml.Unmarshal(xml_result, e) return e } }
func (this *ZoneGroupTopology) CheckForUpdate(updateType UpdateType, cachedOnly bool, version string) (updateItem *UpdateItem, err error) { type UpdateItemHolder struct { XMLName xml.Name UpdateItem } type UpdateItemText struct { XMLName xml.Name Text string `xml:",chardata"` } type Response struct { XMLName xml.Name UpdateItem UpdateItemText ErrorResponse } args := []Arg{ {"UpdateType", updateType}, {"CachedOnly", cachedOnly}, {"Version", version}, } response := this.Svc.Call("CheckForUpdate", args) doc := Response{} xml.Unmarshal([]byte(response), &doc) rec := UpdateItemHolder{} xml.Unmarshal([]byte(doc.UpdateItem.Text), &rec) updateItem = &rec.UpdateItem err = doc.Error() return }
//Delete bucket func (c *AliOSSClient) DeleteBucket(name string) error { uri := fmt.Sprintf("/%s/", name) query := make(map[string]string) header := make(map[string]string) s := &oss_agent{ AccessKey: c.AccessKey, AccessKeySecret: c.AccessKeySecret, Verb: "DELETE", Url: fmt.Sprintf("http://%s.%s", name, c.EndPoint), CanonicalizedHeaders: header, CanonicalizedUri: uri, CanonicalizedQuery: query, Content: &bytes.Reader{}, Debug: c.Debug, logger: c.logger, } v := &BucketList{} e := &AliOssError{} resp, xml_result, err := s.send_request(false) if err != nil { return err } if resp.StatusCode/100 == 2 { xml.Unmarshal(xml_result, v) return nil } else { xml.Unmarshal(xml_result, e) return e } }
func (this *ContentDirectory) Browse(req *BrowseRequest) (browseResult *BrowseResult, err error) { type Response struct { XMLName xml.Name Result string BrowseResult upnpErrorResponse } args := []upnpArg{ {"ObjectID", req.ObjectID}, {"BrowseFlag", req.BrowseFlag}, {"Filter", req.Filter}, {"StartingIndex", req.StartingIndex}, {"RequestedCount", req.RequestCount}, {"SortCriteria", req.SortCriteria}, } response := this.Svc.Call("Browse", args) doc := Response{} xml.Unmarshal([]byte(response), &doc) doc.Doc = &didl.Lite{} // log.Printf("%s", doc.Result) xml.Unmarshal([]byte(doc.Result), doc.Doc) browseResult = &doc.BrowseResult err = doc.Error() return }
func (c *AliOSSClient) GetBucketWebsite(name string) (*BucketWebsite, error) { uri := fmt.Sprintf("/%s/?website", name) query := make(map[string]string) header := make(map[string]string) query["website"] = "" s := &oss_agent{ AccessKey: c.AccessKey, AccessKeySecret: c.AccessKeySecret, Verb: "GET", Url: fmt.Sprintf("http://%s.%s", name, c.EndPoint), CanonicalizedHeaders: header, CanonicalizedUri: uri, CanonicalizedQuery: query, Content: &bytes.Reader{}, ContentType: "application/xml", Debug: c.Debug, logger: c.logger, } v := &BucketWebsite{} e := &AliOssError{} resp, xml_result, err := s.send_request(false) if err != nil { return nil, err } if resp.StatusCode/100 == 2 { xml.Unmarshal(xml_result, v) return v, nil } else { xml.Unmarshal(xml_result, e) return nil, e } }
// ReadEntity checks the Accept header and reads the content into the entityPointer // May be called multiple times in the request-response flow func (r *Request) ReadEntity(entityPointer interface{}) (err error) { contentType := r.Request.Header.Get(HEADER_ContentType) var buffer []byte if r.bodyContent != nil { buffer = *r.bodyContent } else { buffer, err = ioutil.ReadAll(r.Request.Body) r.bodyContent = &buffer if err != nil { return err } } if strings.Contains(contentType, MIME_XML) { return xml.Unmarshal(buffer, entityPointer) } if strings.Contains(contentType, MIME_JSON) { return json.Unmarshal(buffer, entityPointer) } if MIME_XML == defaultRequestContentType { return xml.Unmarshal(buffer, entityPointer) } if MIME_JSON == defaultRequestContentType { return json.Unmarshal(buffer, entityPointer) } return errors.New("[restful] Unable to unmarshal content of type:" + contentType) }
func S3CopyFile(awsAuth *aws.Auth, fromS3Bucket, fromS3Path, toS3Bucket, toS3Path, permissionACL string) error { client := &http.Client{} destinationPath := fmt.Sprintf("http://%v.s3.amazonaws.com/%v", toS3Bucket, toS3Path) req, err := http.NewRequest("PUT", destinationPath, nil) if err != nil { return fmt.Errorf("PUT request on %v failed: %v", destinationPath, err) } req.Header.Add("x-amz-copy-source", fmt.Sprintf("/%v/%v", fromS3Bucket, fromS3Path)) req.Header.Add("x-amz-date", time.Now().Format(time.RFC850)) if permissionACL != "" { req.Header.Add("x-amz-acl", permissionACL) } signaturePath := fmt.Sprintf("/%v/%v", toS3Bucket, toS3Path) SignAWSRequest(*awsAuth, signaturePath, req) resp, err := client.Do(req) if resp == nil { return fmt.Errorf("Nil response received: %v", err) } defer resp.Body.Close() // attempt to read the response body to check for success/error message respBody, respBodyErr := ioutil.ReadAll(resp.Body) if respBodyErr != nil { return fmt.Errorf("Error reading s3 copy response body: %v", respBodyErr) } // Attempt to unmarshall the response body. If there's no errors, it means // that the S3 copy was successful. If there's an error, or a non-200 // response code, it indicates a copy error copyObjectResult := CopyObjectResult{} xmlErr := xml.Unmarshal(respBody, ©ObjectResult) if xmlErr != nil || resp.StatusCode != http.StatusOK { errMsg := "" if xmlErr == nil { errMsg = fmt.Sprintf("S3 returned status code: %d", resp.StatusCode) } else { errMsg = fmt.Sprintf("unmarshalling error: %v", xmlErr) } // an unmarshalling error or a non-200 status code indicates S3 returned // an error so we'll now attempt to unmarshall that error response copyObjectError := CopyObjectError{} xmlErr = xml.Unmarshal(respBody, ©ObjectError) if xmlErr != nil { // *This should seldom happen since a non-200 status code or a // copyObjectResult unmarshall error on a response from S3 should // contain a CopyObjectError. An error here indicates possible // backwards incompatible changes in the AWS API return fmt.Errorf("Unrecognized S3 response: %v: %v", errMsg, xmlErr) } copyObjectError.ErrMsg = errMsg // if we were able to parse out an error reponse, then we can reliably // inform the user of the error return copyObjectError } return err }
func Open(filename string) (*Epub, error) { r, err := zip.OpenReader(filename) if err != nil { return nil, err } // We need r to stay open forever epub := &Epub{Zip: r} mimetype, _ := epub.getFileAsString("mimetype") if mimetype != "application/epub+zip" { return new(Epub), errors.New("Unsupported mime type.") } containerFile, _ := epub.getFile("META-INF/container.xml") c := new(Container) err = xml.Unmarshal(containerFile, c) if err != nil { return nil, err } rootFile, _ := epub.getFile(c.Rootfiles[0].Path) epub.Opfdir = path.Dir(c.Rootfiles[0].Path) pkg := new(Package) err = xml.Unmarshal(rootFile, pkg) if err != nil { return nil, err } epub.Manifest = pkg.Manifest.Items epub.Spine = pkg.Spine.Itemrefs return epub, nil }
func TestComplexSchema(t *testing.T) { ty := &types{ schemas: []*XSDSchema{}, } data := []byte(complex) err := xml.Unmarshal(data, &ty.schemas) if err != nil { t.Error(err) } err = xml.Unmarshal(data, &ty.schemaMetas) if err != nil { t.Error(err) } if ty.schemaMetas[0].xsdPrefix() != "" { t.Error("should have got xsd prefix \"\" got", ty.schemaMetas[0].xsdPrefix()) } if ty.schemaMetas[0].tnsPrefix() != "tns" { t.Error("should have got prefix \"tns\" got", ty.schemaMetas[0].tnsPrefix()) } // ty.genTypes() t.Log(fmt.Printf("%# v\n\n", pretty.Formatter(ty))) }
// Get more detail for a TV show, including information on it's episodes. func (series *Series) GetDetail() (err error) { response, err := http.Get(fmt.Sprintf(GET_DETAIL_URL, API_KEY, strconv.FormatUint(series.Id, 10))) if err != nil { return } data, err := ioutil.ReadAll(response.Body) if err != nil { return } if err = xml.Unmarshal(data, series); err != nil { return } episodeList := EpisodeList{} if err = xml.Unmarshal(data, &episodeList); err != nil { return } if series.Seasons == nil { series.Seasons = make(map[uint64][]Episode) } for _, episode := range episodeList.Episodes { series.Seasons[episode.SeasonNumber] = append(series.Seasons[episode.SeasonNumber], episode) } return }
func parseBody(encryptType, timestamp, nonce, msgSignature string, body []byte) (msg *Message, err error) { msg = &Message{} // 如果报文被加密了,先要验签解密 if encryptType == "aes" { encMsg := &EncMessage{} // 解析加密的 xml err = xml.Unmarshal(body, encMsg) if err != nil { return nil, err } msg.ToUserName = encMsg.ToUserName msg.Encrypt = encMsg.Encrypt if !CheckSignature(Token, timestamp, nonce, encMsg.Encrypt, msgSignature) { return nil, errors.New("check signature error") } body, err = DecryptMsg(encMsg.Encrypt, EncodingAESKey, AppId) if err != nil { return nil, err } log.Debugf("receive: %s", body) } // 解析 xml err = xml.Unmarshal(body, msg) if err != nil { return nil, err } return msg, nil }
func main() { raw, err := ioutil.ReadAll(os.Stdin) if err != nil { panic(err) } var env soap.Envelope if err := xml.Unmarshal(raw, &env); err != nil { panic(err) } fmt.Println(env) var browse Browse err = xml.Unmarshal([]byte(env.Body.Action), &browse) if err != nil { panic(err) } fmt.Println(browse) raw, err = xml.MarshalIndent( GetSortCapabilitiesResponse{ SortCaps: "dc:title", }, "", " ") if err != nil { panic(err) } fmt.Println(string(raw)) }
//parseRequest emulates the SOAP style rpc call by figuring out //which "method" is being called //fix Me: improve performance func (c2b *C2B) parseRequest(r *http.Request) http.HandlerFunc { body, err := ioutil.ReadAll(r.Body) fmt.Println(string(body)) processCheckoutOp := &ProcessCheckoutRequest{} confirmTrxOp := &ConfirmTransactionRequest{} transStatusOp := &TransactionStatusRequest{} err = xml.Unmarshal(body, processCheckoutOp) err = xml.Unmarshal(body, confirmTrxOp) err = xml.Unmarshal(body, transStatusOp) if err != nil { fmt.Println(err) return func(rw http.ResponseWriter, r *http.Request) { rw.WriteHeader(500) rw.Write([]byte(err.Error())) } } operation := processCheckoutOp.Body.ProcessCheckout.XMLName.Local if strings.Contains(operation, "processCheckOut") { return c2b.processCheckout(processCheckoutOp) } operation = confirmTrxOp.Body.ConfirmTransaction.XMLName.Local if strings.Contains(operation, "transactionConfirmRequest") { return c2b.confirmTransaction(confirmTrxOp) } operation = transStatusOp.Body.TransactionStatus.XMLName.Local if strings.Contains(operation, "transactionStatusRequest") { return c2b.transactionStatus(transStatusOp) } return c2b.unknownOperation(operation) }
func TestProfileConstraints(t *testing.T) { Convey("Profile validation should not be nominal", t, func() { Convey("there are no tests", func() { profileData := `<?xml version="1.0" encoding="UTF-8"?><sg name="Basic example" uid="1"><test name="Profile test" critical="1s" warning="750ms"/></sg>` profile := Profile{} xml.Unmarshal([]byte(profileData), &profile) So(profile.Validate(), ShouldNotBeNil) }) Convey("there cookie forwaring is enabled on top request", func() { profileData := `<?xml version="1.0" encoding="UTF-8"?> <sg name="Basic example" uid="1"> <test name="SG test" critical="1s" warning="750ms"> <description>This is the test for SG.</description> <request method="get" responseType="json" repeat="20" useParentCookies="true" concurrency="10"> <url base="http://google.com/search" /> </request> </test> </sg>` profile := Profile{} xml.Unmarshal([]byte(profileData), &profile) So(func() { profile.Validate() }, ShouldNotPanic) }) }) }
func main() { content, err := ioutil.ReadFile("studygolang.xml") if err != nil { log.Fatal(err) } var result Result err = xml.Unmarshal(content, &result) if err != nil { log.Fatal(err) } log.Println(result) log.Println(result.Persons[0].Name) //input := "<?xml version=\"1.0\" encoding=\"GBK\"?><request><head><h_exch_code>800101</h_exch_code><h_bank_no>1111</h_bank_no><h_user_id>1038738897</h_user_id><h_branch_id>B00008211</h_branch_id><h_fact_date>20110321</h_fact_date><h_fact_time>16:28:30</h_fact_time><h_exch_date>20130929</h_exch_date><h_serial_no>123456</h_serial_no><h_rsp_code>hj123545</h_rsp_code><h_rsp_msg>ar</h_rsp_msg></head><body><record><user_pwd>54f9b3396fe28c208d525db21588965c</user_pwd></record></body></request>" //inputReader := strings.NewReader(input) content, err = ioutil.ReadFile("request.xml") decoder := mahonia.NewDecoder("gb18030") r := bufio.NewReader(decoder.NewReader(content)) if err != nil { log.Fatal(err) } log.Println(content) var request Request_800101 err = xml.Unmarshal(content, &request) if err != nil { log.Fatal(err) } log.Println(request) }
func (client *Client) loadResource(method string, url string, r io.Reader, i interface{}) error { dbg.Printf("executing method=%s to url=%s", method, url) req, e := http.NewRequest(method, url, r) if e != nil { return e } client.SignAwsRequestV2(req, time.Now()) rsp, e := http.DefaultClient.Do(req) if e != nil { return e } defer rsp.Body.Close() dbg.Printf("got status %s", rsp.Status) b, e := ioutil.ReadAll(rsp.Body) if e != nil { return e } dbg.Printf("got response %s", b) if rsp.Status[0] != '2' { resp := &ErrorResponse{} if e = xml.Unmarshal(b, resp); e != nil { return e } return resp.Error } return xml.Unmarshal(b, i) }