Maison > développement back-end > Golang > le corps du texte

Fichier docker Golang chromedp

WBOY
Libérer: 2024-02-09 10:09:09
avant
1239 Les gens l'ont consulté

Golang chromedp dockerfile

Dans le développement de logiciels modernes, Docker est devenu un outil indispensable, qui peut aider les développeurs à créer, déployer et gérer rapidement des applications. En tant que langage de programmation efficace et concis, Golang est également privilégié par les développeurs. Alors, comment développer des applications en utilisant Golang dans Docker ? Cet article explique comment écrire un Dockerfile pour une application Golang et utiliser la bibliothèque chromedp pour implémenter des tests Web automatisés. Si vous êtes intéressé par les tests automatisés Golang, Docker et Web, vous souhaiterez peut-être continuer à lire.

Contenu de la question

J'ai un code Golang qui utilise chromedp pour se connecter au chrome local de l'utilisateur Voici mon code :

package main

import (
    "context"
    "fmt"
    "log"
    "os"
    "time"

    "github.com/chromedp/chromedp"
    "github.com/gin-gonic/gin"
)

func main() {
    api := gin.default()

    api.get("api/jwt", func(c *gin.context) {
        opts := append(chromedp.defaultexecallocatoroptions[:],
            chromedp.flag("headless", false),
            chromedp.flag("disable-gpu", true),
            chromedp.flag("no-sandbox", true),
            chromedp.flag("disable-dev-shm-usage", true),
            chromedp.flag("disable-browser-side-navigation", true),
            chromedp.flag("disable-infobars", true),
            chromedp.flag("disable-extensions", true),
            chromedp.flag("disable-notifications", true),
            chromedp.flag("disable-default-apps", true),
            chromedp.flag("disable-background-timer-throttling", true),
            chromedp.flag("disable-backgrounding-occluded-windows", true),
            chromedp.flag("disable-renderer-backgrounding", true),
        )

        allocctx, cancel := chromedp.newexecallocator(context.background(), opts...)
        defer cancel()

        ctx, cancel := chromedp.newcontext(allocctx)
        defer cancel()

        var localstoragedata string // declaração da variável localstoragedata

        err := chromedp.run(ctx,
            chromedp.navigate("https://csonlinetenant.b2clogin.com/csonlinetenant.onmicrosoft.com/oauth2/v2.0/authorize"),
            chromedp.sleep(5*time.second),
            chromedp.waitvisible(`#fgh`),
            chromedp.sendkeys(`#fghfg`, "fghfgh"),
            chromedp.sendkeys(`#xcvxcv`, "xcxcvcxv"),
            chromedp.click(`#thgh`, chromedp.byid),
            chromedp.sleep(5*time.second),
            chromedp.click(`dfgd`, chromedp.byid),
            chromedp.sleep(15*time.second),
            chromedp.evaluateasdevtools(`localstorage.getitem('c')`, &localstoragedata),
        )
        if err != nil {
            log.printf("error: %v", err)
            return
        }

        fmt.println("bearer", localstoragedata)

        // restante do código...

        c.json(200, gin.h{
            "success": localstoragedata,
        })
    })

    listenaddr := os.getenv("listen")

    if val, ok := os.lookupenv("functions_customhandler_port"); ok {
        listenaddr = ":" + val
    }
    if listenaddr == "" {
        listenaddr = ":8080"
    }

    api.run(listenaddr)
}
Copier après la connexion

J'ai donc créé un fichier docker avec ce dont mon client a besoin pour utiliser cette application (j'ai installé Chrome et construit mon golang dans l'image)

fichier docker :

from golang:1.20 as build-stage

workdir /app

# instale as dependências do chrome
run wget -q -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list
run apt-get update && apt-get -y install google-chrome-stable
run chrome &


copy go.mod go.sum ./
run go mod download

copy *.go ./

run cgo_enabled=0 goos=linux go build -o /dockergo

# run the tests in the container
from build-stage as run-test-stage
run go test -v ./...

# deploy the application binary into a lean image
from gcr.io/distroless/base-debian11 as build-release-stage

workdir /

copy --from=build-stage /dockergo /dockergo

expose 8080

user nonroot:nonroot

entrypoint ["/dockergo"]
Copier après la connexion

Image construite avec succès et sans maux de tête Mais lorsque je teste l'image Docker localement, j'obtiens cette erreur :

Error: exec: "google-chrome": executable file not found in $PATH
Copier après la connexion

Que signifie cette erreur ? Mon Chrome ne fonctionne pas ? Comment puis-je l'exécuter ?

Solution de contournement

Le navigateur Chrome est uniquement installé et n'est pas disponible dans l'image finale créée build-stage中。它在 build-release-stage.

J'essaie d'installer Chrome en utilisant ce fichier docker :

# deploy the application binary into a lean image
from gcr.io/distroless/base-debian11 as build-release-stage

run wget -q -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - \
    && echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list
run apt-get update && apt-get -y install google-chrome-stable
run chrome &
Copier après la connexion

Mais cela échoue avec le message suivant :

...
step 2/4 : run wget -q -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -     && echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list
 ---> running in 7596202a5684
failed to create shim task: oci runtime create failed: runc create failed: unable to start container process: exec: "/bin/sh": stat /bin/sh: no such file or directory: unknown
Copier après la connexion

Je pense que vous devez choisir une autre image de base sur laquelle vous pouvez facilement installer Chrome. Une meilleure option consiste à exécuter les tests en utilisant l'image chromedp/headless-shell 作为基础镜像。该图像包含 chrome 的无头 shell,该 shell 非常小。下面的演示 dockerfile 还显示了首先编译测试二进制文件,然后在 chromedp/headless-shell : 

FROM golang:1.20.5-buster AS build-stage

WORKDIR /app

COPY go.mod go.sum ./
RUN go mod download

COPY . .

RUN CGO_ENABLED=0 go build -o dockergo
# Build the test binary
RUN CGO_ENABLED=0 go test -c -o dockergo.test

# Run the tests in the container
FROM chromedp/headless-shell:114.0.5735.199 AS run-test-stage

WORKDIR /app
# Copy other files that is needed to run the test (testdata?).
COPY . .
COPY --from=build-stage /app/dockergo.test ./dockergo.test
RUN /app/dockergo.test -test.v

# Deploy the application binary into a lean image
FROM chromedp/headless-shell:114.0.5735.199 AS build-release-stage

COPY --from=build-stage /app/dockergo /dockergo

EXPOSE 8080

ENTRYPOINT ["/dockergo"]
Copier après la connexion

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Étiquettes associées:
source:stackoverflow.com
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal
À propos de nous Clause de non-responsabilité Sitemap
Site Web PHP chinois:Formation PHP en ligne sur le bien-être public,Aidez les apprenants PHP à grandir rapidement!