公司文件服务截图功能使用的是ChromeDp,为了节省服务器资源,希望将chrome隔离起来。
首先拉取chrome镜像
1
| docker pull chromedp/headless-shell:latest
|
启用镜像
1
| docker run -d -p 9222:9222 --rm --name headless-shell --shm-size 2G chromedp/headless-shell
|
代码实例如下:
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
| package main import ( "context" "github.com/chromedp/chromedp" "log" "os" ) func main() { devtoolsWsURL := "ws://127.0.0.1:9222" allocatorContext, cancel := chromedp.NewRemoteAllocator(context.Background(), devtoolsWsURL) defer cancel() ctx, cancel := chromedp.NewContext(allocatorContext) defer cancel() var res []byte err := chromedp.Run(ctx, chromedp.Navigate("https://www.baidu.com"),chromedp.FullScreenshot(&res, 100)); if err != nil { log.Fatalf("Failed navigate baidu.com: %v", err) return } create, err := os.Create("a.png") if err != nil { return } defer create.Close()
create.Write(res) }
|