Golang Web page Download Example

Source: Internet
Author: User


package main/* *  Chinese coding Problem  */import  ("errors" "Flag" "FMT" query  "github.com/ Puerkitobio/goquery "" Golang.org/x/text/encoding/simplifiedchinese "" Io/ioutil "" Net/http "" OS "" Path/filepath "" Runtime "" Strings "" Sync ") var  (np = runtime. NUMCPU () _  = runtime. Gomaxprocs (NP)) Var wg sync. waitgrouptype folder struct {url stringdir string}type file struct { Url  stringdir  stringname string}func checkerr (Err error)  {if  Err != nil {fmt. Printf ("%v\n",  err. Error ()) OS. Exit (1)}}FUNC DECODETOGBK (text string)   (string, error)  {dst := make ([]byte,  len (Text) * *) Tr := simplifiedchinese. GB18030. Newdecoder () ndst, _, err := tr. Transform (Dst, []byte (text),  true) If err != nil {return text, err} Return string (DST[:NDST]),  NIL}FUNC PRInteach (index int, item *query. Selection)  {fmt. Println ("selection: ",  item. Text ())}func isdir (path string)  bool {return strings. Hassuffix (path,  "/")}func makefolder (item *query. selection, url, dir string)   (f *folder, err error)  {tx :=  Item. Text () Href, ok := item. Attr ("href") name, err := decodetogbk (TX) If err != nil {return}if !ok  {err = errors. New ("makefolder : "  + tx +  " href attribute not present") return}f = &folder{ Url: url + href, dir: filepath. Join (Dir, name)}return}func makefile (item *query. selection, url, dir string)   (f *file, err error)  {tx := item . Text () Href, ok := item. Attr ("href") if !ok {err = errors. New ("makefile : "  + tx +  " href attribute not Present") RETURN}NAME, ERR := DECODETOGBK (TX) if err !=  nil {return}f = &file{url: url + href, dir: dir, name:  name}return}func crawl (url, localdir string)  {doc, err := query. NewDocument (URL)// checkerr (err) if err != nil {fmt. Printf ("%v\n",  err. Error ()) Return}items := doc. Find ("a") dir := localdirif !strings. Hassuffix (url,  "/")  {url +=  "/"}crawleach := func (i int, item * Query. Selection)  {tx := item. Text () If isdir (TX)  {folder, err := makefolder (ITEM, URL, DIR) If err  != nil {fmt. Printf ("%v\n",  err. Error ()) RETURN}WG. ADD (1) Go crawlfolder (folder)} else {file, err := makefile (item, url,  DIR) if err != nil {fmt. Printf ("%v\n ",  err. Error ()) return}download (file)}}items. Each (Crawleach)}func download (file *file)  {dir := file. Dirurl := file. Urlname := file. Nameif err := os. Mkdirall (Dir, os. modeperm);  os. Isexist (Err)  {fmt. Printf ("%x is exist\n",  dir)} else {os. Chmod (Dir, os. Modeperm)}resp, err := http. Get (URL) if err != nil {fmt. Printf ("%v\n",  err. Error ()) Return}defer resp. Body.close () Body, err := ioutil. ReadAll (resp. Body) if err != nil {fmt. Printf ("%v\n",  err. Error ()) return}fp := string ([]rune (filepath. Join (Dir, name))) Err = ioutil. WriteFile (fp, body, 0777) if err != nil {fmt. Printf ("%v fp:[%v]\n",  err. Error (),  FP) return}fmt. Printf ("download: %+v\n",  file)}func crawlfolder (folder *folder)  {url :=  Folder. urldir : = folder. Dircrawl (URL, DIR) WG. Done ()}func main ()  {host := flag. String ("host",  "http://localhost:8000",  "HTTP Service address host") Location := flag. String ("Locate",  "E:/crawler download File",  "Local file system absolute path") flag. Parse () crawl (*host, *location) WG. Wait ()}





Golang Web page Download Example

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.