JFrog Go Client SDK

repository·master·Indexed 42 days ago

https://github.com/jfrog/jfrog-client-go

A Go-based SDK for interacting with JFrog platform services, providing programmatic access to JFrog Artifactory, Xray, and Distribution. The library enables developers to manage files, build info, access tokens, API keys, and repositories (Local, Remote, Virtual, and Federated) directly from Go applications.

Tokens
28.6K
Snippets
73
Records
79
Agent score
54%

What's inside JFrog Go Client

  1. How to use ContentReader for large data sets

    master

    Some APIs return a content.ContentReader struct. This is designed to handle large amounts of data safely by streaming it, preventing high memory consumption.

    To use a ContentReader:

    1. Iterate through records: Use reader.NextRecord(currentResult) to populate a pointer to a result type (e.g., *utils.ResultItem) with the next available record. This method returns nil when there are no more records.
    2. Handle errors: Always check reader.GetError() after the iteration loop to catch any errors that occurred during the streaming process.
    3. Cleanup: Use reader.Close() to remove the temporary file used by the reader. It is best practice to call this via defer immediately after obtaining the reader.
    4. Reuse (Optional): You can call reader.Reset() to move the pointer back to the beginning of the output for a second pass, provided the reader has not been closed.
    reader, err := servicesManager.SearchFiles(searchParams)
    if err != nil {
        return err
    }
    
    // Remove the data file used by the reader.
    defer func() {
        if reader != nil {
            err = reader.Close()
        }
    }()
    
    // Iterate over the results.
    for currentResult := new(utils.ResultItem); reader.NextRecord(currentResult) == nil; currentResult = new(utils.ResultItem)  { 
        fmt.Printf("Found artifact: %s of type: %s\n", currentResult.Name, currentResult.Type)
    }
    
    if err := reader.GetError(); err != nil {
        return err
    }
    
    // Resets the reader pointer back to the beginning of the output.
    // Make sure not to call this method after the reader had been closed.
    reader.Reset()
  2. Use jfrog-client-go as a Go module

    master
    The jfrog-client-go library provides Go APIs to perform actions on JFrog Artifactory, Xray, and Distribution directly from your Go applications. To use it, add the module to your project's go.mod file. Note that because the project is relatively new, APIs may change frequently between releases.
  3. Initialize the Xray Service Manager

    master

    To use Xray APIs, you must first create XrayDetails, build a serviceConfig using the config.NewConfigBuilder(), and then instantiate an xray.New manager. If your authentication token is scoped to a specific project, use .SetProjectKey("project") on the manager instance.

    xrayDetails := auth.NewXrayDetails()
    xrayDetails.SetUrl("http://localhost:8081/xray")
    xrayDetails.SetSshKeyPath("path/to/.ssh/")
    xrayDetails.SetApiKey("apikey")
    xrayDetails.SetUser("user")
    xrayDetails.SetPassword("password")
    xrayDetails.SetAccessToken("accesstoken")
    // if client certificates are required
    xrayDetails.SetClientCertPath("path/to/.cer")
    xrayDetails.SetClientCertKeyPath("path/to/.key")
    
    serviceConfig, err := config.NewConfigBuilder().
        SetServiceDetails(xrayDetails).
        SetCertificatesPath(certPath).
        SetHttpRetries(8).
        Build()
    
    // Create manager
    xrayManager, err := xray.New(serviceConfig)
    
    // If token is project-scoped
    xrayManager, err = xray.New(serviceConfig).SetProjectKey("project")
  4. Run integration tests

    master

    To run integration tests, you must have a running JFrog instance. Use the go test command with the -tags itest flag. You can filter tests using specific test type flags and provide connection details via command-line flags.

    go test -v github.com/jfrog/jfrog-client-go/tests -timeout 0 -tags itest [test-types] [flags]
  5. Create and Update Repositories (Local, Remote, Virtual, Federated)

    master

    Repositories can be managed via the servicesManager. Each repository type (Local, Remote, Virtual, Federated) supports specific package types (e.g., Maven, Docker, NPM, Go, etc.).

    Patterns

    1. Typed Parameters: Use services.New<PackageType><RepoType>Params() to get a specialized struct for that specific package type.
    2. Base Parameters: Use services.New<RepoType>BaseParams() for a generic configuration that works across multiple package types.

    Examples

    Local Generic Repository

    params := services.NewGenericLocalRepositoryParams()
    params.Key = "generic-repo"
    params.Description = "This is a public description"
    params.RepoLayoutRef = "simple-default"
    // ... other params
    err = servicesManager.CreateLocalRepository().Generic(params)

    Remote Maven Repository

    params := services.NewMavenRemoteRepositoryParams()
    params.Key = "maven-central-remote"
    params.Url = "https://repo.maven.apache.org"
    params.RepoLayoutRef = "maven-2-default"
    // ... other params
    err = servicesManager.CreateRemoteRepository().Maven(params)

    Virtual Go Repository

    params := services.NewGoVirtualRepositoryParams()
    params.Key = "go-virtual"
    params.Repositories = []string{"gocenter-remote", "go-local"}
    // ... other params
    err = servicesManager.CreateVirtualRepository().Go(params)

    Federated Generic Repository

    params := services.NewGenericFederatedRepositoryParams()
    params.Key = "federated-repo"
    params.Members = []services.FederatedRepositoryMemberParams{
        {Url: "http://targetartifactory/artifactory/federatedRepositoryName", Enabled: true},
    }
    err = servicesManager.CreateFederatedRepository().Generic(params)
  6. Create an XSC Service Manager

    master

    To interact with XSC (Xray Service Center) services, you must first initialize XscDetails, build a serviceConfig using the config.NewConfigBuilder(), and then instantiate the manager using xsc.New(serviceConfig).

    Steps:

    1. Initialize XscDetails: Use auth.NewXscDetails() and set the URL, authentication (API key, user/password, or access token), and optional client certificates.
    2. Build Config: Use config.NewConfigBuilder() to attach the details and optionally set the SetHttpRetries value (defaults to 3).
    3. Instantiate Manager: Call xsc.New(serviceConfig).
    xscDetails := auth.NewXscDetails()
    xscDetails.SetUrl("http://localhost:8081/xsc")
    xscDetails.SetApiKey("apikey")
    // ... set other credentials
    
    serviceConfig, err := config.NewConfigBuilder().
        SetServiceDetails(xscDetails).
        SetHttpRetries(8).
        Build()
    
    xscManager, err := xsc.New(serviceConfig)
  7. Initialize Artifactory Service Manager

    master

    To interact with Artifactory, you must first create ArtifactoryDetails, build a serviceConfig using config.NewConfigBuilder(), and finally instantiate an Artifactory manager using artifactory.New(serviceConfig).

    ArtifactoryDetails supports various authentication methods including API Keys, Access Tokens, Username/Password, and Client Certificates. You can also provide a custom http.Client to the configuration builder to handle custom proxy settings or transport logic.

    // 1. Define Artifactory connection details
    rtDetails := auth.NewArtifactoryDetails()
    rtDetails.SetUrl("http://localhost:8081/artifactory")
    rtDetails.SetApiKey("apikey")
    rtDetails.SetUser("user")
    
    // 2. Build the service configuration
    serviceConfig, err := config.NewConfigBuilder().
        SetServiceDetails(rtDetails).
        SetDialTimeout(180 * time.Second).
        SetHttpRetries(8).
        Build()
    
    // 3. Create the manager
    rtManager, err := artifactory.New(serviceConfig)
  8. Manage Groups in JFrog

    master

    You can manage user groups using the serviceManager. This includes fetching all groups, retrieving specific group details, creating new groups, updating existing ones, and deleting groups.

    Note on fetching group details: If you request a group that does not exist, the method returns a nil value for the group parameter and a nil error.

    // Fetch all groups
    groups, err := serviceManager.GetAllGroups()
    
    // Fetch specific group details
    params := services.NewGroupParams()
    params.GroupDetails.Name = "myGroupName"
    params.IncludeUsers = true // Set to true to receive associated usernames
    group, err := serviceManager.GetGroup(params)
    
    // Create a group
    params := services.NewGroupParams()
    params.GroupDetails.Name = "myGroupName"
    params.GroupDetails.Description = "Description"
    params.GroupDetails.AutoJoin = &falseValue
    params.GroupDetails.AdminPrivileges = &trueValue
    params.GroupDetails.Realm = "internal"
    params.GroupDetails.UsersNames = []string{"UserA", "UserB"}
    params.ReplaceIfExists = false
    err := serviceManager.CreateGroup(params)
    
    // Update a group
    params.GroupDetails.Description = "Newer Description"
    params.GroupDetails.UsersNames = []string{"UserC"} // Adds UserC to existing members
    err := serviceManager.UpdateGroup(params)
    
    // Delete a group
    err := serviceManager.DeleteGroup("myGroupName")
  9. Initialize the Access Service Manager

    master

    To interact with JFrog Access services (like managing projects, tokens, and groups), you must first create AccessDetails, build a serviceConfig using a ConfigBuilder, and then initialize the access.New manager. You can provide authentication via URL, SSH keys, API keys, username/password, access tokens, or client certificates.

    accessDetails := accessAuth.NewAccessDetails()
    accessDetails.SetUrl("http://localhost:8081/access/")
    accessDetails.SetApiKey("apikey")
    accessDetails.SetUser("user")
    accessDetails.SetPassword("password")
    
    serviceConfig, err := clientConfig.NewConfigBuilder().
        SetServiceDetails(accessAuth).
        SetInsecureTls(accessDetails.InsecureTls).
        Build()
    
    accessManager, err := access.New(serviceConfig)
  10. Manage Artifactory storage and package info

    master

    Use the serviceManager to interact with Artifactory storage metadata and package lead files.

    // Get storage summary info
    storageInfo, err := serviceManager.GetStorageInfo()
    
    // Trigger a recalculation of storage info
    err := serviceManager.CalculateStorageInfo()
    
    // Get the package lead file
    leadArtifact, err := serviceManager.GetPackageLeadFile()