package main

import (
	"fmt"
	"golang.org/x/net/html"
	"log"
	"net/http"
)

type man struct {
	sex    bool
	name   string
	action func()
}

func main() {

	var dug man
	dug.name = "dugulingping"
	dug.action = func() {
		fmt.Println("Hi " + dug.name)
	}
	fmt.Printf("%T\n", dug.action)
	dug.action()

	resp, err := http.Get("https://golang-china.github.io/gopl-zh/ch5/ch5-02.html")
	if err != nil {
		log.Fatal(err)
	}
	if resp.StatusCode != http.StatusOK {
		err := resp.Body.Close()
		if err != nil {
			log.Fatal(err)
			return
		}
	}
	doc, err := html.Parse(resp.Body)
	if err != nil {
		log.Fatal(err)
		return
	}
	// 关闭链接
	err = resp.Body.Close()
	if err != nil {
		log.Fatal(err)
		return
	}
	node := make(map[string]int)
	v(node, doc)
	//fmt.Println(node)

}

func v(node map[string]int, n *html.Node) map[string]int {
	if n == nil {
		return node
	}
	if n.Type == html.ElementNode {
		node[n.Data] += 1
		//fmt.Println(n.Data)
	}

	if n.Type == html.TextNode {
		if n.Data != "script" && n.Data != "style" {
			//fmt.Println(n.Data)
		}
	}
	node = v(node, n.FirstChild)
	node = v(node, n.NextSibling)
	return node
}
func v4(links []string, n *html.Node) []string {
	if n == nil {
		return links
	}
	if n.Type == html.ElementNode && (n.Data == "a" || n.Data == "images" || n.Data == "scripts") {
		for _, a := range n.Attr {
			if a.Key == "href" {
				links = append(links, a.Val)
				//fmt.Println(a.Val)
			}
		}
	}
	links = v4(links, n.FirstChild)
	links = v4(links, n.NextSibling)
	return links
}
