Why is the headless mode not working in Chrome? - selenium

in golang
"github.com/fedesog/webdriver"
I'm using a package, I need a headless mode, I've coded as below, but it doesn't work, I don't know why. Do you know what the problem is?
chromeDriver := webdriver.NewChromeDriver("./chromedriver")
err := chromeDriver.Start()
if err != nil {
log.Println(err)
}
desired := webdriver.Capabilities{"Platform": "mac", "arguments": []string{"--headless", "--disable-gpu", "--window-size=1920,1200", "--ignore-certificate-errors", "--disable-extensions", "--no-sandbox", "--disable-dev-shm-usage"}}
required := webdriver.Capabilities{"arguments": []string{"--headless", "--disable-gpu", "--window-size=1920,1200", "--ignore-certificate-errors", "--disable-extensions", "--no-sandbox", "--disable-dev-shm-usage"}}
session, err := chromeDriver.NewSession(desired, required)
if err != nil {
panic(err.Error())
}

Related

how to launch my own browser version with selenium using go?

package main
import (
"fmt"
"time"
"github.com/tebeka/selenium"
"github.com/tebeka/selenium/chrome"
)
func main() {
// Run Chrome browser
service, err := selenium.NewChromeDriverService("./chromedriver", 4444)
if err != nil {
panic(err)
}
defer service.Stop()
caps := selenium.Capabilities{}
caps.AddChrome(chrome.Capabilities{Args: []string{
"window-size=1920x1080",
"--no-sandbox",
"--disable-dev-shm-usage",
"disable-gpu",
// "--headless", // comment out this line to see the browser
}})
driver, err := selenium.NewRemote(caps, "")
if err != nil {
panic(err)
}
driver.Get("https://google.com")
time.Sleep(50e+10)
The code above makes a new clear version of chrome browser. In my case I need to open my default one with my cookies and other data (no tabs needed).
I haven't found a method using Go programming language. I found a solution for a C# language (i guess) here it is
ChromeOptions options = new ChromeOptions(); options.setBinary("/path/to/other/chrome/binary");
but I'm noob and i don't know how to convert it to fit in my code.
Thanks for any help
UPDATE
I tryed this. But it doesn't work anyway :c
package main
import (
"fmt"
"time"
"github.com/tebeka/selenium"
"github.com/tebeka/selenium/chrome"
)
func main() {
// Run Chrome browser
service, err := selenium.NewChromeDriverService("./chromedriver", 4444)
if err != nil {
panic(err)
}
defer service.Stop()
caps := selenium.Capabilities{}
caps.AddChrome(chrome.Capabilities{
Path: "C:/Program Files/Google/Chrome/Application/chrome.exe",
Args: []string{
"window-size=1920x1080",
"--no-sandbox",
"--disable-dev-shm-usage",
"--disable-gpu",
"--user-data-dir=C:/Users/nikit/AppData/Local/Google/Chrome/User Data/Profile 2",
// "--headless", // comment out this line to see the browser
}})
driver, err := selenium.NewRemote(caps, "")
if err != nil {
panic(err)
}
driver.Get("https://point.wb.ru/login")
elem, _ := driver.FindElement(selenium.ByClassName, "opp-form")
if elem != nil {
fmt.Println("нашел!")
}
time.Sleep(time.Second * 100)
}

Go how to use cookiejar for multiple requests?

I'm trying to make a cli for a site that has csrf, needing the csrf token to be sent on headers and on a form.
I can't seem to understand net/http.Client or net/http/cookieJar
This its even good practice? There's a better way of doing csrf login on Go ?
Thx in advance ^v^
This its my code:
package main
import (
"fmt"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
"strings"
"time"
)
var (
httpClient = &http.Client{}
)
func main() {
jar, err := cookiejar.New(nil)
if err != nil {
log.Fatal(err)
}
httpClient = &http.Client{
Timeout: 30 * time.Second,
Jar: jar,
}
requestURL := "https://example.com/"
res, err := httpClient.Get(requestURL)
if err != nil {
log.Fatal(err)
}
log.Println(res.Cookies())
// stdout: cookie as expected
u := &url.URL{}
u.Parse(requestURL)
log.Println(httpClient.Jar.Cookies(u))
// stdout: []
form := make(url.Values)
/* ... */
req, err := http.NewRequest(http.MethodPost, requestURL, strings.NewReader(form.Encode()))
if err != nil {
fmt.Printf("client: could not create request: %s\n", err)
}
res, err = httpClient.Do(req)
if err != nil {
log.Fatal(err)
}
fmt.Println(req)
// stdout: cookie as expected
}

AWS Workdocs file upload

I have a use case where I need to upload csv files to workdocs. I'm using golang language and I receive the error as "The request signature we calculated does not match the signature you provided." I'm using InitiateDocumentVersionUpload with IAM user credentials. Can you please help me as what might be causing this error.
optionsWd := workdocs.Options{Credentials: credentials.NewStaticCredentialsProvider(request.AccessKeyId, request.SecretAccessKey, ""),
Region: "us-east-1"}
client := workdocs.New(optionsWd)
folderId := "e38c72c9ae6918109b573a17ece5f24e7a353374672b627b1b3b54918354cd5e"
docName := "testdoc"
docType := "text/csv"
data, err := r.S3.GetGetObject(ctx, "test-bucket", s3Path)
params := workdocs.InitiateDocumentVersionUploadInput{
ParentFolderId: &folderId,
Name: &docName,
ContentType: &docType,
}
res, err := client.InitiateDocumentVersionUpload(ctx, &params)
if err != nil {
fmt.Println(err)
}
fmt.Println(res.Metadata)
resval := *res.UploadMetadata
urlVal := *resval.UploadUrl
signedHeadVal := resval.SignedHeaders
fmt.Println(urlVal)
fmt.Println(signedHeadVal)
metadata := *res.Metadata
fmt.Println(metadata)
fmt.Println(signedHeadVal)
wdclient := &http.Client{}
req, err := http.NewRequest(http.MethodPut, urlVal, strings.NewReader(data))
if err != nil {
fmt.Println(err)
}
req.Header.Set("Content-Type", "text/csv")
signer := v4.NewSigner()
credsVal := aws.Credentials{
AccessKeyID: aws.ToString(&request.AccessKeyId),
SecretAccessKey: aws.ToString(&request.SecretAccessKey),
SessionToken: "",
}
requestBodyBytes, _ := ioutil.ReadAll(req.Body)
sha := sha256.Sum256(requestBodyBytes)
payloadHash := hex.EncodeToString(sha[:])
if err != nil {
fmt.Println(err)
}
signer.SignHTTP(req.Context(), credsVal, req, payloadHash, "s3", "us-east-1", time.Now())
_, err = wdclient.Do(req)
if err != nil {
fmt.Println(err)
}
I tried the code mentioned above and unable to resolve the error. Expectation is to upload the file in workdocs.

Unable to execute a command inside a docker container

I am trying to spin up a Postgres container via the Docker Go SDK. I can get the container started, and I copy my SQL file into the container and verified the file is there.
I cannot run this file, which right now just contains CREATE TABLE tester;
Here is my Go code that I am trying to use:
package gosqlcontainer
import (
"archive/tar"
"bufio"
"bytes"
"context"
"fmt"
"io"
"log"
"os"
"os/exec"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
)
func StartContainer() string {
ctx := context.Background()
cli, err := client.NewClientWithOpts(client.WithAPIVersionNegotiation())
if err != nil {
panic(err)
}
imageName := "postgres"
out, err := cli.ImagePull(ctx, imageName, types.ImagePullOptions{})
if err != nil {
panic(err)
}
defer out.Close()
io.Copy(os.Stdout, out)
container, err := cli.ContainerCreate(ctx, &container.Config{
Image: imageName, Env: []string{"POSTGRES_PASSWORD=password"},
}, nil, nil, nil, "")
if err != nil {
panic(err)
}
if err := cli.ContainerStart(ctx, container.ID, types.ContainerStartOptions{}); err != nil {
panic(err)
}
tarFile := TarFile("test.sql")
if err = cli.CopyToContainer(ctx, container.ID, "/home/", tarFile, types.CopyToContainerOptions{AllowOverwriteDirWithFile: true}); err != nil {
fmt.Println("error copying to container", err)
}
time.Sleep(1 * time.Second)
execCommand, err := cli.ContainerExecCreate(ctx, container.ID, types.ExecConfig{AttachStdin: true, AttachStderr: true, AttachStdout: true, Cmd: []string{"psql", "-U postgres -f /home/test.sql"}})
if err != nil {
fmt.Println("exec err is", err)
}
if err := cli.ContainerExecStart(ctx, execCommand.ID, types.ExecStartCheck{}); err != nil {
fmt.Println("Err Start", err)
}
return container.ID
}
When I try to do this from CLI, I can run that file and verify that the DB is created. However, programmatically it does not work, and I do not see any errors returned.
The goal is for this to be a library I can reference to spin up a container, import data, and used for integration tests. I am currently calling it from a basic client locally, using go run main.go I am working on macOS Monterey v12.4

400 Bad Request for frappe.cloud API

I'm getting 400 Bad Request for frappe.cloud API, when I'm trying to call it using golang code using http.NewRequest, this API is working fine when I check it using postman. following is the API
https://xxxx.frappe.cloud/api/resource/Item?fields=["name","item_name","item_group","description"]&filters=[["Item","item_group","=","xxx Product"]]
If I use the same golang code to call same API with out filters it works fine. following is the working API
https://xxxx.frappe.cloud/api/resource/Item?fields=["name","item_name","item_group","description"]
code as follows
func FetchProperties(dataChannel models.DataChannel) (map[string]interface{}, error) {
thisMap := make(map[string][]map[string]interface{})
client := &http.Client{}
req, err := http.NewRequest("GET", dataChannel.APIPath, nil)
if err != nil {
commons.ErrorLogger.Println(err.Error())
return nil, err
}
eds, err := GetDecryptedEDSByEDSID(dataChannel.EDSId)
if err != nil {
commons.ErrorLogger.Println(err.Error())
return nil, &commons.RequestError{StatusCode: 400, Err: err}
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", eds.DataSource.Auth.Token)
response, err := client.Do(req)
if err != nil {
commons.ErrorLogger.Println(err.Error())
return nil, err
}
data, err := ioutil.ReadAll(response.Body)
if err != nil {
commons.ErrorLogger.Println(err.Error())
return nil, &commons.RequestError{StatusCode: 400, Err: err}
}
if response.StatusCode == 200 {
err = json.Unmarshal(data, &thisMap)
if err != nil {
commons.ErrorLogger.Println(err.Error())
return nil, &commons.RequestError{StatusCode: 400, Err: err}
}
return thisMap["data"][0], err
} else {
return nil, &commons.RequestError{StatusCode: response.StatusCode, Err: errors.New("getting " + strconv.Itoa(response.StatusCode) + " From Data channel API")}
}
Postman has an option to convert request to programming language equivalent.
Here is a working go code for sending the request. package main
import (
"fmt"
"strings"
"net/http"
"io/ioutil"
)
func main() {
url := "https://xxx.frappe.cloud/api/resource/Item?fields=%5B%22name%22,%22item_name%22,%22item_group%22,%22description%22%5D&filters=%5B%5B%22Item%22,%22item_group%22,%22=%22,%22xxx%20Product%22%5D%5D%0A"
method := "GET"
payload := strings.NewReader(`{
"payload": {},
"url_key": "",
"req_type": ""
}`)
client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Cookie", "full_name=foo; sid=secret_sid; system_user=yes; user_id=foobar; user_image=")
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}