{"id":23138238,"url":"https://github.com/softlayer/softlayer-go","last_synced_at":"2025-04-12T23:41:32.737Z","repository":{"id":10932325,"uuid":"67535946","full_name":"softlayer/softlayer-go","owner":"softlayer","description":"SoftLayer API Client for the Go Language","archived":false,"fork":false,"pushed_at":"2024-06-06T22:20:53.000Z","size":3882,"stargazers_count":52,"open_issues_count":8,"forks_count":46,"subscribers_count":16,"default_branch":"master","last_synced_at":"2024-06-21T15:20:16.169Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/softlayer.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2016-09-06T18:33:08.000Z","updated_at":"2024-06-06T22:20:21.000Z","dependencies_parsed_at":"2024-02-14T20:18:10.184Z","dependency_job_id":"92e1c61e-4243-4178-b0a5-1d85d68a18d5","html_url":"https://github.com/softlayer/softlayer-go","commit_stats":null,"previous_names":[],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/softlayer%2Fsoftlayer-go","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/softlayer%2Fsoftlayer-go/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/softlayer%2Fsoftlayer-go/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/softlayer%2Fsoftlayer-go/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/softlayer","download_url":"https://codeload.github.com/softlayer/softlayer-go/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248647256,"owners_count":21139081,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-12-17T13:10:17.664Z","updated_at":"2025-04-12T23:41:32.716Z","avatar_url":"https://github.com/softlayer.png","language":"Go","readme":"# softlayer-go\n\n[![Build Status](https://github.com/softlayer/softlayer-go/actions/workflows/go.yml/badge.svg?branch=master)](https://github.com/softlayer/softlayer-go/actions/workflows/go.yml)\n[![GoDoc](https://godoc.org/github.com/softlayer/softlayer-go?status.svg)](https://godoc.org/github.com/softlayer/softlayer-go)\n[![License](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](http://www.apache.org/licenses/LICENSE-2.0)\n[![Coverage Status](https://coveralls.io/repos/github/softlayer/softlayer-go/badge.svg?branch=master)](https://coveralls.io/github/softlayer/softlayer-go?branch=master)\n\nThe Official and Complete SoftLayer API Client for Golang (the Go programming language).\n\n## Introduction\n\nThis library contains a complete implementation of the SoftLayer API for client application development in the Go programming language. Code for each API data type and service method is pre-generated, using the SoftLayer API metadata endpoint as input, thus ensuring 100% coverage of the API right out of the gate.\n\nIt was designed to feel as natural as possible for programmers familiar with other popular SoftLayer SDKs, and attempts to minimize unnecessary boilerplate and type assertions where possible.\n\n## Usage\n\n### Basic example:\n\nThree easy steps:\n\n```go\n// 1. Create a session\nsess := session.New(username, apikey)\n\n// 2. Get a service\naccountService := services.GetAccountService(sess)\n\n// 3. Invoke a method:\naccount, err := accountService.GetObject()\n```\n\n[More examples](https://github.com/softlayer/softlayer-go/tree/master/examples)\n\n### Sessions\n\nIn addition to the example above, sessions can also be created using values\nset in the environment, or from the local configuration file (i.e. ~/.softlayer):\n\n```go\nsess := session.New()\n```\n\nIn this usage, the username, API key, and endpoint are read from specific environment\nvariables, then the local configuration file (i.e. ~/.softlayer).  First match ends\nthe search:\n\n* _Username_\n\t1. environment variable `SL_USERNAME`\n\t1. environment variable `SOFTLAYER_USERNAME`\n\t1. local config `username`.\n* _API Key_\n\t1. environment variable `SL_API_KEY`\n\t1. environment variable `SOFTLAYER_API_KEY`\n\t1. local config `api_key`.\n* _Endpoint_\n\t1. environment variable `SL_ENDPOINT_URL`\n\t1. environment variable `SOFTLAYER_ENDPOINT_URL`\n\t1. local config `endpoint_url`.\n* _Timeout_\n\t1. environment variable `SL_TIMEOUT`\n\t1. environment variable `SOFTLAYER_TIMEOUT`\n\t1. local config `timeout`.\n\n*Note:* Endpoint defaults to `https://api.softlayer.com/rest/v3` if not configured through any of the above methods. Timeout defaults to 120 seconds.\n\nExample of the **~/.softlayer** local configuration file:\n```\n[softlayer]\nusername = \u003cyour username\u003e\napi_key = \u003cyour api key\u003e\nendpoint_url = \u003coptional\u003e\ntimeout = \u003coptional\u003e\n```\n\n### Instance methods\n\nTo call a method on a specific instance, set the instance ID before making the call:\n\n```go\nservice := services.GetUserCustomerService(sess)\n\nservice.Id(6786566).GetObject()\n```\n\n### Passing Parameters\n\nAll non-slice method parameters are passed as pointers. This is to allow for optional values to be omitted (by passing `nil`)\n\n```go\nguestId := 123456\nuserCustomerService.RemoveVirtualGuestAccess(\u0026guestId)\n```\n\nFor convenience, a set of helper functions exists that allocate storage for a literal and return a pointer. The above can be refactored to:\n\n```go\nuserCustomerService.RemoveVirtualGuestAccess(sl.Int(123456))\n```\n\n### Using datatypes\n\nA complete library of SoftLayer API data type structs exists in the `datatypes` package. Like method parameters, all non-slice members are declared as pointers. This has the advantage of permitting updates without re-sending the complete data structure (since `nil` values are omitted from the resulting JSON). Use the same set of helper functions to assist in populating individual members.\n\n```go\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/softlayer/softlayer-go/datatypes\"\n\t\"github.com/softlayer/softlayer-go/services\"\n\t\"github.com/softlayer/softlayer-go/session\"\n\t\"github.com/softlayer/softlayer-go/sl\"\n)\n\nfunc main() {\n\tsess := session.New() // See above for details about creating a new session\n\n\t// Get the Virtual_Guest service\n\tservice := services.GetVirtualGuestService(sess)\n\n\t// Create a Virtual_Guest struct as a template\n\tvGuestTemplate := datatypes.Virtual_Guest{\n\t\t// Set Creation values - use helpers from the sl package to set pointer values.\n\t\t// Unset (nil) values are not sent\n\t\tHostname:                     sl.String(\"sample\"),\n\t\tDomain:                       sl.String(\"example.com\"),\n\t\tMaxMemory:                    sl.Int(4096),\n\t\tStartCpus:                    sl.Int(1),\n\t\tDatacenter:                   \u0026datatypes.Location{Name: sl.String(\"wdc01\")},\n\t\tOperatingSystemReferenceCode: sl.String(\"UBUNTU_LATEST\"),\n\t\tLocalDiskFlag:                sl.Bool(true),\n\t}\n\n\t// Tell the API to create the virtual guest\n\tnewGuest, err := service.CreateObject(\u0026vGuestTemplate)\n\t// optional error checking...\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Print the ID of the new guest.  Don't forget to dereference\n\tfmt.Printf(\"New guest %d created\", *newGuest.Id)\n}\n```\n\n### Object Masks, Filters, Result Limits\n\nObject masks, object filters, and pagination (limit and offset) can be set\nby calling the `Mask()`, `Filter()`, `Limit()` and `Offset()` service methods\nprior to invoking an API method.\n\nFor example, to set an object mask and filter that will be applied to\nthe results of the Account.GetObject() method:\n\n```go\naccountService := services.GetAccountService(sess)\n\naccountService.\n\tMask(\"id;hostname\").\n\tFilter(`{\"virtualGuests\":{\"domain\":{\"operation\":\"example.com\"}}}`).\n\tGetObject()\n```\n\nThe mask and filter are applied to the current request only, and reset after the\nmethod returns. To preserve these options for future requests, save the return value:\n\n```go\naccountServiceWithMaskAndFilter = accountService.Mask(\"id;hostname\").\n\tFilter(`{\"virtualGuests\":{\"domain\":{\"operation\":\"example.com\"}}}`)\n```\n\nResult limits are specified as separate `Limit` and `Offset` values:\n\n```go\naccountService.\n\tOffset(100).      // start at the 100th element in the list\n\tLimit(25).        // limit to 25 results\n\tGetVirtualGuests()\n```\n\n#### Filter Builder\n\nThere is also a **filter builder** you can use to create a _Filter_ instead of writing out the raw string:\n\n```go\n// requires importing the filter package\naccountServiceWithMaskAndFilter = accountService.\n    Mask(\"id;hostname\").\n    Filter(filter.Path(\"virtualGuests.domain\").Eq(\"example.com\").Build())\n```\n\nYou can also create a filter incrementally:\n\n```go\n// Create initial filters\nfilters := filter.New(\n    filter.Path(\"virtualGuests.hostname\").StartsWith(\"KM078\"),\n    filter.Path(\"virtualGuests.id\").NotEq(12345),\n)\n\n// ....\n// Later, append another filter\nfilters = append(filters, filter.Path(\"virtualGuests.domain\").Eq(\"example.com\"))\n\naccountServiceWithMaskAndFilter = accountService.\n    Mask(\"id;hostname\").\n    Filter(filters.Build())\n```\n\nOr you can build all those filters in one step:\n\n```go\n// Create initial filters\nfilters := filter.Build(\n    filter.Path(\"virtualGuests.hostname\").StartsWith(\"KM078\"),\n    filter.Path(\"virtualGuests.id\").NotEq(12345),\n    filter.Path(\"virtualGuests.domain\").Eq(\"example.com\"),\n)\n\naccountServiceWithMaskAndFilter = accountService.\n    Mask(\"id;hostname\").Filter(filters)\n```\n\nSee _filter/filters.go_ for the full range of operations supported.\nThe file at _examples/filters.go_ will show additional examples.\nAlso, [this is a good article](https://sldn.softlayer.com/article/object-filters) that describes SoftLayer filters at length.\n\n### Handling Errors\n\nFor any error that occurs within one of the SoftLayer API services, a custom\nerror type is returned, with individual fields that can be parsed separately.\n\n```go\n_, err := service.Id(0).      // invalid object ID\n\tGetObject()\n\nif err != nil {\n\t// Note: type assertion is only necessary for inspecting individual fields\n\tapiErr := err.(sl.Error)\n\tfmt.Printf(\"API Error:\")\n\tfmt.Printf(\"HTTP Status Code: %d\\n\", apiErr.StatusCode)\n\tfmt.Printf(\"API Code: %s\\n\", apiErr.Exception)\n\tfmt.Printf(\"API Error: %s\\n\", apiErr.Message)\n}\n```\n\nNote that `sl.Error` implements the standard `error` interface, so it can\nbe handled like any other error, if the above granularity is not needed:\n\n```go\n_, err := service.GetObject()\nif err != nil {\n\tfmt.Println(\"Error during processing: \", err)\n}\n```\n\n### Session Options\n\nTo set a different endpoint (e.g., the backend network endpoint):\n\n```go\nsession.Endpoint = \"https://api.service.softlayer.com/rest/v3\"\n```\n\nTo enable debug output:\n\n```go\nsession.Debug = true\n```\n\nBy default, the debug output is sent to standard output. You can customize this by setting up your own logger:\n\n```go\nimport \"github.com/softlayer/softlayer-go/session\"\n\nsession.Logger = log.New(os.Stderr, \"[CUSTOMIZED] \", log.LstdFlags)\n```\n\nYou can also tell the session to retry the api requests if there is a timeout error:\n\n```go\n// Specify how many times to retry the request, the request timeout, and how much time to wait\n// between retries.\nservices.GetVirtualGuestService(\n\tsess.SetTimeout(900).SetRetries(2).SetRetryWait(3)\n).GetObject(...)\n```\n\n### Password-based authentication\n\nPassword-based authentication (via requesting a token from the API) is\nonly supported when talking to the API using the XML-RPC transport protocol.\n\nTo use the XML-RPC protocol, simply specify an XML-RPC endpoint url:\n\n```go\nfunc main() {\n    // Create a session specifying an XML-RPC endpoint url.\n    sess := \u0026session.Session{\n        Endpoint: \"https://api.softlayer.com/xmlrpc/v3\",\n    }\n\n    // Get a token from the api using your username and password\n    userService := services.GetUserCustomerService(sess)\n    token, err := userService.GetPortalLoginToken(username, password, nil, nil)\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    // Add user id and token to the session.\n    sess.UserId = *token.UserId\n    sess.AuthToken = *token.Hash\n\n    // You have a complete authenticated session now.\n    // Call any api from this point on as normal...\n    keys, err := userService.Id(sess.UserId).GetApiAuthenticationKeys()\n    if err != nil {\n        log.Fatal(err)\n    }\n\n    log.Println(\"API Key:\", *keys[0].AuthenticationKey)\n}\n```\n\n### IAM authentication\n\nThis library supports [IBM's IAM Authentication](https://cloud.ibm.com/docs/account?topic=account-iamoverview) (used by the `ibmcloud` cli for example). You will want to set the `IAMToken` and `IAMRefreshToken` properties on the session to make use of it.\n\n\n```go\ntoken := \"Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...\"\nrefreshToken := \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb...\"\nsess := \u0026session.Session{\n\tEndpoint:         \"https://api.softlayer.com/rest/v3.1\",\n\tDebug:            true,\n\tTimeout:          90,\n\tIAMToken:         token,\n\tIAMRefreshToken:  refreshToken\n}\n```\n\nYou can bypass automatic IAM refresh by either not setting the `IAMRefreshToken` property, or by manually configuring the `TransportHandler`\n\n```go\ntoken := \"Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...\"\nhandler := \u0026session.RestTransport{}\nsess := \u0026session.Session{\n\tEndpoint:         \"https://api.softlayer.com/rest/v3.1\",\n\tDebug:            true,\n\tTimeout:          90,\n\tIAMToken:         token,\n\tTransportHandler  handler,\n}\n```\n\nIf you want to be able to record the new tokens in a config file (or elsewhere), you can configure an `IAMUpdaters` Observer which will take in as arguments the new tokens, allowing you to save them somewhere for reuse.\n\n```go\ntype MyIamUpdater struct {\n\tdebug bool\n}\n// This function is where you can configure the logic to save these new tokens somewhere\nfunc (iamupdater *MyIamUpdater) Update(token string, refresh string) {\n\tfmt.Printf(\"[DEBUG] New Token: %s\\n\", token)\n\tfmt.Printf(\"[DEBUG] New Refresh Token: %s\\n\", refresh)\n}\nupdater := \u0026MyIamUpdater{debug: false}\ntoken := \"Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa...\"\nrefreshToken := \"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb...\"\nsess := \u0026session.Session{\n\tEndpoint:         \"https://api.softlayer.com/rest/v3.1\",\n\tIAMToken:         token,\n\tIAMRefreshToken  refreshToken,\n}\nsess.AddIAMUpdater(updater)\n```\nYou can add multiple Updaters as well, they will be called in the order they are added. `MyIamUpdater.Update(token, refresh)` in this example will only be called when the token is actually refreshed.\n\n## Running Examples\n\nThe [Examples](https://github.com/softlayer/softlayer-go/tree/master/examples) directory has a few rough examples scripts that can help you get started developing with this library.\n\nThe Examples have their own modules since there are a few dependencies here not needed in the normal softlayer-go repo.\nThe following will get you started:\n\n```bash\ncd examples\ngo mod vendor\ngo run main.go  --help\n```\n\nThe examples use [SPF13's Cobra Command](https://github.com/spf13/cobra) library to build little command examples, which should be easy enough to \nexpand upon if needed. The [SoftLayer-CLI](https://github.com/softlayer/softlayer-cli) project is also a good example of how to use the softlayer-go library.\n\n\n## Development\n\n### Setup\n\nTo get _softlayer-go_:\n\n```\ngo get github.com/softlayer/softlayer-go/...\n```\n\n### Build\n\n```\nmake\n```\n\n```bash\ngofmt -w `find . -name '*.go' | grep -v vendor`\ngo vet -all $(go list ./... | grep -v datatypes)\ngo get -d -v ./...\ngo build ./...\n\n```\n\n### Test\n\n```\nmake test\n```\n\n```bash\ngofmt -w `find . -name '*.go' | grep -v vendor`\ngo generate ./session\ngo vet -all $(go list ./... | grep -v datatypes)\ngo mod vendor\ngo test $(go list ./... | grep -v '/vendor/') -timeout=30s -coverprofile coverage.out\n```\n\n### Updating dependencies\n\n```\nmake update_deps\n```\n\n### Generate\nThis downloads the API definitions and creates go files for them.\n\n(with make)\n```bash\nmake generate\n```\n\n(manually)\n```bash\ngo run ./tools generate\n```\n\n\n## Copyright\n\nThis software is Copyright (c) 2016-2024 IBM Corp. See the bundled LICENSE file for more information.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsoftlayer%2Fsoftlayer-go","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsoftlayer%2Fsoftlayer-go","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsoftlayer%2Fsoftlayer-go/lists"}