JFrog Go Client SDK
repository·master·Indexed 42 days ago
https://github.com/jfrog/jfrog-client-goA 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.
What's inside JFrog Go Client
- The JFrog Go Client is a Go library designed to interact with JFrog platform services. It provides programmatic access to JFrog capabilities within Go applications.
How to use ContentReader for large data sets
masterSome APIs return a
content.ContentReaderstruct. This is designed to handle large amounts of data safely by streaming it, preventing high memory consumption.To use a
ContentReader:- 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 returnsnilwhen there are no more records. - Handle errors: Always check
reader.GetError()after the iteration loop to catch any errors that occurred during the streaming process. - Cleanup: Use
reader.Close()to remove the temporary file used by the reader. It is best practice to call this viadeferimmediately after obtaining the reader. - 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()- Iterate through records: Use
Use jfrog-client-go as a Go module
masterThejfrog-client-golibrary 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'sgo.modfile. Note that because the project is relatively new, APIs may change frequently between releases.Initialize the Xray Service Manager
masterTo use Xray APIs, you must first create
XrayDetails, build aserviceConfigusing theconfig.NewConfigBuilder(), and then instantiate anxray.Newmanager. 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")Run integration tests
masterTo run integration tests, you must have a running JFrog instance. Use the
go testcommand with the-tags itestflag. 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]Create and Update Repositories (Local, Remote, Virtual, Federated)
masterRepositories 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
- Typed Parameters: Use
services.New<PackageType><RepoType>Params()to get a specialized struct for that specific package type. - 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)- Typed Parameters: Use
Create an XSC Service Manager
masterTo interact with XSC (Xray Service Center) services, you must first initialize
XscDetails, build aserviceConfigusing theconfig.NewConfigBuilder(), and then instantiate the manager usingxsc.New(serviceConfig).Steps:
- Initialize XscDetails: Use
auth.NewXscDetails()and set the URL, authentication (API key, user/password, or access token), and optional client certificates. - Build Config: Use
config.NewConfigBuilder()to attach the details and optionally set theSetHttpRetriesvalue (defaults to 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)- Initialize XscDetails: Use
Initialize Artifactory Service Manager
masterTo interact with Artifactory, you must first create
ArtifactoryDetails, build aserviceConfigusingconfig.NewConfigBuilder(), and finally instantiate an Artifactory manager usingartifactory.New(serviceConfig).ArtifactoryDetailssupports various authentication methods including API Keys, Access Tokens, Username/Password, and Client Certificates. You can also provide a customhttp.Clientto 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)Export the full system
masterUse the
Exportmethod on theserviceManagerto generate a full system export. You must provide a destination path viaNewExportParams.params := services.NewExportParams("/tmp/") err := serviceManager.Export(params)Manage Groups in JFrog
masterYou 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
nilvalue for the group parameter and anilerror.// 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")Initialize the Access Service Manager
masterTo interact with JFrog Access services (like managing projects, tokens, and groups), you must first create
AccessDetails, build aserviceConfigusing aConfigBuilder, and then initialize theaccess.Newmanager. 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)Manage Artifactory storage and package info
masterUse the
serviceManagerto 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()