Search code examples
gogoogle-drive-apigoogle-docsgoogle-docs-api

Share Google Doc via Golang SDK


I am using service account JSON to create google Doc via Golang SDK but as this doc is only accessible to Service account I am not able to access it with my Personal Google Account. In the Google Doc SDK documentation I couldn't find any function to share the Doc.

This is my sample Code:

package googledoc

import (
    "context"
    "fmt"

    log "github.com/sirupsen/logrus"
    "golang.org/x/oauth2/google"
    "google.golang.org/api/docs/v1"
    "google.golang.org/api/option"

func CreateDoc(title string) error {
    ctx := context.Background()
    cred, err := GetSecrets("ap-south-1", "GOOGLE_SVC_ACC_JSON")
    if err != nil {
        return fmt.Errorf("unable to get the SSM %v", err)
    }

    config, err := google.JWTConfigFromJSON(cred, docs.DocumentsScope)
    if err != nil {
        log.Fatalf("Unable to parse client secret file to config: %v", err)
    }
    client := config.Client(ctx)
    srv, err := docs.NewService(ctx, option.WithHTTPClient(client))
    if err != nil {
        log.Fatalf("Unable to retrieve Docs client: %v", err)
    }

    docObj := docs.Document{
        Title: title,
    }

    doc, err := srv.Documents.Create(&docObj).Do()
    if err != nil {
        log.Fatalf("Unable to retrieve data from document: %v", err)
        return err
    }
    fmt.Printf("The title of the doc is: %s %s\n", doc.Title, doc.DocumentId)
    return nil
}

Any help with this would be really appreciated Thanks.


Solution

  • I believe your goal is as follows.

    • You want to share the created Google Document by the service account with your Google account.
    • You want to achieve this using googleapis for golang.

    Unfortunately, Google Docs API cannot be used for sharing the Document with users. In this case, Drive API is used. When your script is modified using Drive API, how about the following modification?

    Sample script:

    Please add this script just after the line of fmt.Printf("The title of the doc is: %s %s\n", doc.Title, doc.DocumentId). By this, the created Google Document is shared with the user.

    driveSrv, err := drive.NewService(ctx, option.WithHTTPClient(client)) // Please use your client and service for using Drive API.
    if err != nil {
        log.Fatal(err)
    }
    permission := &drive.Permission{
        EmailAddress: "###", // Please set the email address you want to share.
        Role:         "writer",
        Type:         "user",
    }
    res, err := driveSrv.Permissions.Create(doc.DocumentId, permission).Do()
    if err != nil {
        log.Fatal(err)
        return err
    }
    fmt.Println(res)
    
    • When this script is added to your script, the created Document is shared with the user as the writer.

    Reference: