From ccb91f470e7f6d48d57ad38260e441dade8dac50 Mon Sep 17 00:00:00 2001 From: jim teeuwen Date: Wed, 25 Nov 2009 02:50:06 +0100 Subject: [PATCH] Added *document.LoadUri() method to load documents from the web (over http) --- src/document.go | 18 ++++++++++++++++++ src/io.go | 1 + src/xmlx_test.go | 17 ++++++++++++++++- 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/src/document.go b/src/document.go index 9fd7665..bd8c9c1 100644 --- a/src/document.go +++ b/src/document.go @@ -32,6 +32,7 @@ import "io" import "strings" import "xml" import "fmt" +import "http" type Document struct { Version string; @@ -207,6 +208,23 @@ func (this *Document) LoadFile(path string) (err os.Error) { return; } +func (this *Document) LoadUri(uri string) (err os.Error) { + r, _, err := http.Get(uri); + if err != nil { + return + } + + defer r.Body.Close(); + + b, err := io.ReadAll(r.Body); + if err != nil { + return + } + + err = this.LoadString(string(b)); + return; +} + func (this *Document) LoadStream(r *io.Reader) (err os.Error) { content := ""; buff := make([]byte, 256); diff --git a/src/io.go b/src/io.go index 37ecb80..19ad58d 100644 --- a/src/io.go +++ b/src/io.go @@ -4,6 +4,7 @@ import "os" import "io" type ILoader interface { + LoadUrl(string) os.Error; LoadFile(string) os.Error; LoadString(string) os.Error; LoadStream(*io.Reader) os.Error; diff --git a/src/xmlx_test.go b/src/xmlx_test.go index d64474c..dd07a09 100644 --- a/src/xmlx_test.go +++ b/src/xmlx_test.go @@ -2,7 +2,7 @@ package xmlx import "testing" -func TestDoc(t *testing.T) { +func TestLoadLocal(t *testing.T) { doc := New(); err := doc.LoadFile("test.xml"); @@ -17,6 +17,21 @@ func TestDoc(t *testing.T) { } } +func TestLoadRemote(t *testing.T) { + doc := New(); + err := doc.LoadUri("http://tldp.org/authors/template/Sample-HOWTO.xml"); + + if err != nil { + t.Errorf("%s", err); + return; + } + + if len(doc.Root.Children) == 0 { + t.Errorf("Root node has no children."); + return; + } +} + func TestSave(t *testing.T) { doc := New(); err := doc.LoadFile("test.xml");