...

Source file src/github.com/playwright-community/playwright-go/examples/download/main.go

Documentation: github.com/playwright-community/playwright-go/examples/download

     1  //go:build ignore
     2  // +build ignore
     3  
     4  package main
     5  
     6  import (
     7  	"fmt"
     8  	"log"
     9  	"net/http"
    10  
    11  	"github.com/playwright-community/playwright-go"
    12  )
    13  
    14  func assertErrorToNilf(message string, err error) {
    15  	if err != nil {
    16  		log.Fatalf(message, err)
    17  	}
    18  }
    19  
    20  func main() {
    21  	startHttpServer()
    22  
    23  	pw, err := playwright.Run()
    24  	assertErrorToNilf("could not launch playwright: %w", err)
    25  	browser, err := pw.Chromium.Launch(playwright.BrowserTypeLaunchOptions{
    26  		Headless: playwright.Bool(true),
    27  	})
    28  	assertErrorToNilf("could not launch Chromium: %w", err)
    29  	context, err := browser.NewContext()
    30  	assertErrorToNilf("could not create context: %w", err)
    31  	page, err := context.NewPage()
    32  	assertErrorToNilf("could not create page: %w", err)
    33  	_, err = page.Goto("http://localhost:1234")
    34  	assertErrorToNilf("could not goto: %w", err)
    35  	assertErrorToNilf("could not set content: %w", page.SetContent(`<a href="/download" download>download</a>`))
    36  	download, err := page.ExpectDownload(func() error {
    37  		return page.Click("text=download")
    38  	})
    39  	assertErrorToNilf("could not download: %w", err)
    40  	fmt.Println(download.SuggestedFilename())
    41  	assertErrorToNilf("could not close browser: %w", browser.Close())
    42  	assertErrorToNilf("could not stop Playwright: %w", pw.Stop())
    43  }
    44  
    45  func startHttpServer() {
    46  	http.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) {
    47  		w.Header().Add("Content-Type", "application/octet-stream")
    48  		w.Header().Add("Content-Disposition", "attachment; filename=file.txt")
    49  		if _, err := w.Write([]byte("foobar")); err != nil {
    50  			log.Printf("could not write: %v", err)
    51  		}
    52  	})
    53  	go func() {
    54  		log.Fatal(http.ListenAndServe(":1234", nil))
    55  	}()
    56  }
    57  

View as plain text