1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| package main
import ( "context" "fmt" "github.com/chromedp/cdproto/cdp" "github.com/chromedp/cdproto/page" "github.com/chromedp/chromedp" "github.com/gin-gonic/gin" )
var ChromeCtx context.Context var AllocateCancel context.Context var Cancel context.CancelFunc
func main(){ Ctx, Cancel = initContext() g := gin.Default() g.Handle("GET", "/", func(c *gin.Context) { url := c.Query("url") visit(url) }) g.Run(":8888")
defer AllocateCancel() defer Cancel() } func initContext() (context.Context, context.CancelFunc) { opts := append( chromedp.DefaultExecAllocatorOptions[:], chromedp.DisableGPU, chromedp.Flag("headless", false), chromedp.Flag("enable-automation", false), chromedp.Flag("restore-on-startup", false), )
allocCtx,AllocateCtx := chromedp.NewExecAllocator(context.Background(),opts..)
ctx, cancel := chromedp.NewContext(allocCtx) _ = chromedp.Run(ctx, chromedp.Navigate("about:blank")) return ctx, cancel }
func visit(url string){ tmpCtx, tmpCancel := chromedp.NewContext(Ctx) if err := chromedp.Run(tmpCtx, chromedp.Navigate(url)); err != nil { panic(err) }
err := page.Close().Do(cdp.WithExecutor(tmpCtx, chromedp.FromContext(tmpCtx).Target)) if err != nil { fmt.Println(err) return } Ctx,Cancel = tmpCtx,tmpCancel }
|