Exemple #1
0
func ExampleParse() {
	s := `<p>Links:</p><ul><li><a href="foo">Foo</a><li><a href="/bar/baz">BarBaz</a></ul>`
	doc, err := html.Parse(strings.NewReader(s))
	if err != nil {
		log.Fatal(err)
	}
	var f func(*html.Node)
	f = func(n *html.Node) {
		if n.Type == html.ElementNode && n.Data == "a" {
			for _, a := range n.Attr {
				if a.Key == "href" {
					fmt.Println(a.Val)
					break
				}
			}
		}
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			f(c)
		}
	}
	f(doc)
	// Output:
	// foo
	// /bar/baz
}
Exemple #2
0
// Opens up the index.html file and adds additional (mostly plugin) elements
func finishIndex(filename string) {
	log.Print("Finishing index file")

	fileReader, err := os.Open(filename)
	if err != nil {
		log.Fatal(err)
	}
	//Parse the html document
	doc, err := html.Parse(fileReader)
	if err != nil {
		log.Fatal(err)
	}
	//Find the HEAD
	var processNode func(*html.Node)
	processNode = func(node *html.Node) {
		if node.Type == html.ElementNode && node.Data == "head" {
			enabledPlugins := fserv.GetEnabledPlugins()
			for _, plugin := range enabledPlugins {
				name := plugin.Name
				css := plugin.Stylesheet
				if css != "" {
					path := "/app/plugin/" + name + "/resource/" + css
					//Construct a new link css node and add it to the head
					attributes := []html.Attribute{
						html.Attribute{Key: "rel", Val: "stylesheet"},
						html.Attribute{Key: "type", Val: "text/css"},
						html.Attribute{Key: "href", Val: path},
					}
					linkNode := html.Node{
						Type: html.ElementNode,
						Data: "link",
						Attr: attributes,
					}
					node.AppendChild(&linkNode)
				}
			}
		}
		for c := node.FirstChild; c != nil; c = c.NextSibling {
			processNode(c)
		}
	}
	processNode(doc)
	var b bytes.Buffer
	html.Render(&b, doc)
	indexHtml = b.String()
	fileReader.Close()
}