{"id":29167181,"url":"https://github.com/onkernel/kernel-go-sdk","last_synced_at":"2025-07-25T22:08:03.589Z","repository":{"id":299124871,"uuid":"983778856","full_name":"onkernel/kernel-go-sdk","owner":"onkernel","description":null,"archived":false,"fork":false,"pushed_at":"2025-07-21T15:51:48.000Z","size":324,"stargazers_count":0,"open_issues_count":2,"forks_count":0,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-07-21T17:51:46.547Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"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/onkernel.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-05-14T22:51:49.000Z","updated_at":"2025-07-16T16:32:53.000Z","dependencies_parsed_at":"2025-06-14T20:42:30.450Z","dependency_job_id":"6c546418-7fcf-4a42-a8ba-8f479d36988b","html_url":"https://github.com/onkernel/kernel-go-sdk","commit_stats":null,"previous_names":["onkernel/kernel-go-sdk"],"tags_count":22,"template":false,"template_full_name":null,"purl":"pkg:github/onkernel/kernel-go-sdk","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/onkernel%2Fkernel-go-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/onkernel%2Fkernel-go-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/onkernel%2Fkernel-go-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/onkernel%2Fkernel-go-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/onkernel","download_url":"https://codeload.github.com/onkernel/kernel-go-sdk/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/onkernel%2Fkernel-go-sdk/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":267070322,"owners_count":24030970,"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","status":"online","status_checked_at":"2025-07-25T02:00:09.625Z","response_time":70,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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":"2025-07-01T09:08:07.612Z","updated_at":"2025-07-25T22:08:03.570Z","avatar_url":"https://github.com/onkernel.png","language":"Go","readme":"# Kernel Go API Library\n\n\u003ca href=\"https://pkg.go.dev/github.com/onkernel/kernel-go-sdk\"\u003e\u003cimg src=\"https://pkg.go.dev/badge/github.com/onkernel/kernel-go-sdk.svg\" alt=\"Go Reference\"\u003e\u003c/a\u003e\n\nThe Kernel Go library provides convenient access to the [Kernel REST API](https://docs.onkernel.com)\nfrom applications written in Go.\n\nIt is generated with [Stainless](https://www.stainless.com/).\n\n## Installation\n\n\u003c!-- x-release-please-start-version --\u003e\n\n```go\nimport (\n\t\"github.com/onkernel/kernel-go-sdk\" // imported as kernel\n)\n```\n\n\u003c!-- x-release-please-end --\u003e\n\nOr to pin the version:\n\n\u003c!-- x-release-please-start-version --\u003e\n\n```sh\ngo get -u 'github.com/onkernel/kernel-go-sdk@v0.8.2'\n```\n\n\u003c!-- x-release-please-end --\u003e\n\n## Requirements\n\nThis library requires Go 1.18+.\n\n## Usage\n\nThe full API of this library can be found in [api.md](api.md).\n\n```go\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/onkernel/kernel-go-sdk\"\n\t\"github.com/onkernel/kernel-go-sdk/option\"\n)\n\nfunc main() {\n\tclient := kernel.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),     // defaults to os.LookupEnv(\"KERNEL_API_KEY\")\n\t\toption.WithEnvironmentDevelopment(), // defaults to option.WithEnvironmentProduction()\n\t)\n\tbrowser, err := client.Browsers.New(context.TODO(), kernel.BrowserNewParams{\n\t\tPersistence: kernel.BrowserPersistenceParam{\n\t\t\tID: \"browser-for-user-1234\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", browser.SessionID)\n}\n\n```\n\n### Request fields\n\nThe kernel library uses the [`omitzero`](https://tip.golang.org/doc/go1.24#encodingjsonpkgencodingjson)\nsemantics from the Go 1.24+ `encoding/json` release for request fields.\n\nRequired primitive fields (`int64`, `string`, etc.) feature the tag \u003ccode\u003e\\`json:\"...,required\"\\`\u003c/code\u003e. These\nfields are always serialized, even their zero values.\n\nOptional primitive types are wrapped in a `param.Opt[T]`. These fields can be set with the provided constructors, `kernel.String(string)`, `kernel.Int(int64)`, etc.\n\nAny `param.Opt[T]`, map, slice, struct or string enum uses the\ntag \u003ccode\u003e\\`json:\"...,omitzero\"\\`\u003c/code\u003e. Its zero value is considered omitted.\n\nThe `param.IsOmitted(any)` function can confirm the presence of any `omitzero` field.\n\n```go\np := kernel.ExampleParams{\n\tID:   \"id_xxx\",             // required property\n\tName: kernel.String(\"...\"), // optional property\n\n\tPoint: kernel.Point{\n\t\tX: 0,             // required field will serialize as 0\n\t\tY: kernel.Int(1), // optional field will serialize as 1\n\t\t// ... omitted non-required fields will not be serialized\n\t},\n\n\tOrigin: kernel.Origin{}, // the zero value of [Origin] is considered omitted\n}\n```\n\nTo send `null` instead of a `param.Opt[T]`, use `param.Null[T]()`.\nTo send `null` instead of a struct `T`, use `param.NullStruct[T]()`.\n\n```go\np.Name = param.Null[string]()       // 'null' instead of string\np.Point = param.NullStruct[Point]() // 'null' instead of struct\n\nparam.IsNull(p.Name)  // true\nparam.IsNull(p.Point) // true\n```\n\nRequest structs contain a `.SetExtraFields(map[string]any)` method which can send non-conforming\nfields in the request body. Extra fields overwrite any struct fields with a matching\nkey. For security reasons, only use `SetExtraFields` with trusted data.\n\nTo send a custom value instead of a struct, use `param.Override[T](value)`.\n\n```go\n// In cases where the API specifies a given type,\n// but you want to send something else, use [SetExtraFields]:\np.SetExtraFields(map[string]any{\n\t\"x\": 0.01, // send \"x\" as a float instead of int\n})\n\n// Send a number instead of an object\ncustom := param.Override[kernel.FooParams](12)\n```\n\n### Request unions\n\nUnions are represented as a struct with fields prefixed by \"Of\" for each of it's variants,\nonly one field can be non-zero. The non-zero field will be serialized.\n\nSub-properties of the union can be accessed via methods on the union struct.\nThese methods return a mutable pointer to the underlying data, if present.\n\n```go\n// Only one field can be non-zero, use param.IsOmitted() to check if a field is set\ntype AnimalUnionParam struct {\n\tOfCat *Cat `json:\",omitzero,inline`\n\tOfDog *Dog `json:\",omitzero,inline`\n}\n\nanimal := AnimalUnionParam{\n\tOfCat: \u0026Cat{\n\t\tName: \"Whiskers\",\n\t\tOwner: PersonParam{\n\t\t\tAddress: AddressParam{Street: \"3333 Coyote Hill Rd\", Zip: 0},\n\t\t},\n\t},\n}\n\n// Mutating a field\nif address := animal.GetOwner().GetAddress(); address != nil {\n\taddress.ZipCode = 94304\n}\n```\n\n### Response objects\n\nAll fields in response structs are ordinary value types (not pointers or wrappers).\nResponse structs also include a special `JSON` field containing metadata about\neach property.\n\n```go\ntype Animal struct {\n\tName   string `json:\"name,nullable\"`\n\tOwners int    `json:\"owners\"`\n\tAge    int    `json:\"age\"`\n\tJSON   struct {\n\t\tName        respjson.Field\n\t\tOwner       respjson.Field\n\t\tAge         respjson.Field\n\t\tExtraFields map[string]respjson.Field\n\t} `json:\"-\"`\n}\n```\n\nTo handle optional data, use the `.Valid()` method on the JSON field.\n`.Valid()` returns true if a field is not `null`, not present, or couldn't be marshaled.\n\nIf `.Valid()` is false, the corresponding field will simply be its zero value.\n\n```go\nraw := `{\"owners\": 1, \"name\": null}`\n\nvar res Animal\njson.Unmarshal([]byte(raw), \u0026res)\n\n// Accessing regular fields\n\nres.Owners // 1\nres.Name   // \"\"\nres.Age    // 0\n\n// Optional field checks\n\nres.JSON.Owners.Valid() // true\nres.JSON.Name.Valid()   // false\nres.JSON.Age.Valid()    // false\n\n// Raw JSON values\n\nres.JSON.Owners.Raw()                  // \"1\"\nres.JSON.Name.Raw() == \"null\"          // true\nres.JSON.Name.Raw() == respjson.Null   // true\nres.JSON.Age.Raw() == \"\"               // true\nres.JSON.Age.Raw() == respjson.Omitted // true\n```\n\nThese `.JSON` structs also include an `ExtraFields` map containing\nany properties in the json response that were not specified\nin the struct. This can be useful for API features not yet\npresent in the SDK.\n\n```go\nbody := res.JSON.ExtraFields[\"my_unexpected_field\"].Raw()\n```\n\n### Response Unions\n\nIn responses, unions are represented by a flattened struct containing all possible fields from each of the\nobject variants.\nTo convert it to a variant use the `.AsFooVariant()` method or the `.AsAny()` method if present.\n\nIf a response value union contains primitive values, primitive fields will be alongside\nthe properties but prefixed with `Of` and feature the tag `json:\"...,inline\"`.\n\n```go\ntype AnimalUnion struct {\n\t// From variants [Dog], [Cat]\n\tOwner Person `json:\"owner\"`\n\t// From variant [Dog]\n\tDogBreed string `json:\"dog_breed\"`\n\t// From variant [Cat]\n\tCatBreed string `json:\"cat_breed\"`\n\t// ...\n\n\tJSON struct {\n\t\tOwner respjson.Field\n\t\t// ...\n\t} `json:\"-\"`\n}\n\n// If animal variant\nif animal.Owner.Address.ZipCode == \"\" {\n\tpanic(\"missing zip code\")\n}\n\n// Switch on the variant\nswitch variant := animal.AsAny().(type) {\ncase Dog:\ncase Cat:\ndefault:\n\tpanic(\"unexpected type\")\n}\n```\n\n### RequestOptions\n\nThis library uses the functional options pattern. Functions defined in the\n`option` package return a `RequestOption`, which is a closure that mutates a\n`RequestConfig`. These options can be supplied to the client or at individual\nrequests. For example:\n\n```go\nclient := kernel.NewClient(\n\t// Adds a header to every request made by the client\n\toption.WithHeader(\"X-Some-Header\", \"custom_header_info\"),\n)\n\nclient.Browsers.New(context.TODO(), ...,\n\t// Override the header\n\toption.WithHeader(\"X-Some-Header\", \"some_other_custom_header_info\"),\n\t// Add an undocumented field to the request body, using sjson syntax\n\toption.WithJSONSet(\"some.json.path\", map[string]string{\"my\": \"object\"}),\n)\n```\n\nThe request option `option.WithDebugLog(nil)` may be helpful while debugging.\n\nSee the [full list of request options](https://pkg.go.dev/github.com/onkernel/kernel-go-sdk/option).\n\n### Pagination\n\nThis library provides some conveniences for working with paginated list endpoints.\n\nYou can use `.ListAutoPaging()` methods to iterate through items across all pages:\n\nOr you can use simple `.List()` methods to fetch a single page and receive a standard response object\nwith additional helper methods like `.GetNextPage()`, e.g.:\n\n### Errors\n\nWhen the API returns a non-success status code, we return an error with type\n`*kernel.Error`. This contains the `StatusCode`, `*http.Request`, and\n`*http.Response` values of the request, as well as the JSON of the error body\n(much like other response objects in the SDK).\n\nTo handle errors, we recommend that you use the `errors.As` pattern:\n\n```go\n_, err := client.Browsers.New(context.TODO(), kernel.BrowserNewParams{\n\tPersistence: kernel.BrowserPersistenceParam{\n\t\tID: \"browser-for-user-1234\",\n\t},\n})\nif err != nil {\n\tvar apierr *kernel.Error\n\tif errors.As(err, \u0026apierr) {\n\t\tprintln(string(apierr.DumpRequest(true)))  // Prints the serialized HTTP request\n\t\tprintln(string(apierr.DumpResponse(true))) // Prints the serialized HTTP response\n\t}\n\tpanic(err.Error()) // GET \"/browsers\": 400 Bad Request { ... }\n}\n```\n\nWhen other errors occur, they are returned unwrapped; for example,\nif HTTP transport fails, you might receive `*url.Error` wrapping `*net.OpError`.\n\n### Timeouts\n\nRequests do not time out by default; use context to configure a timeout for a request lifecycle.\n\nNote that if a request is [retried](#retries), the context timeout does not start over.\nTo set a per-retry timeout, use `option.WithRequestTimeout()`.\n\n```go\n// This sets the timeout for the request, including all the retries.\nctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)\ndefer cancel()\nclient.Browsers.New(\n\tctx,\n\tkernel.BrowserNewParams{\n\t\tPersistence: kernel.BrowserPersistenceParam{\n\t\t\tID: \"browser-for-user-1234\",\n\t\t},\n\t},\n\t// This sets the per-retry timeout\n\toption.WithRequestTimeout(20*time.Second),\n)\n```\n\n### File uploads\n\nRequest parameters that correspond to file uploads in multipart requests are typed as\n`io.Reader`. The contents of the `io.Reader` will by default be sent as a multipart form\npart with the file name of \"anonymous_file\" and content-type of \"application/octet-stream\".\n\nThe file name and content-type can be customized by implementing `Name() string` or `ContentType()\nstring` on the run-time type of `io.Reader`. Note that `os.File` implements `Name() string`, so a\nfile returned by `os.Open` will be sent with the file name on disk.\n\nWe also provide a helper `kernel.File(reader io.Reader, filename string, contentType string)`\nwhich can be used to wrap any `io.Reader` with the appropriate file name and content type.\n\n```go\n// A file from the file system\nfile, err := os.Open(\"/path/to/file\")\nkernel.DeploymentNewParams{\n\tEntrypointRelPath: \"src/app.py\",\n\tFile:              file,\n}\n\n// A file from a string\nkernel.DeploymentNewParams{\n\tEntrypointRelPath: \"src/app.py\",\n\tFile:              strings.NewReader(\"my file contents\"),\n}\n\n// With a custom filename and contentType\nkernel.DeploymentNewParams{\n\tEntrypointRelPath: \"src/app.py\",\n\tFile:              kernel.File(strings.NewReader(`{\"hello\": \"foo\"}`), \"file.go\", \"application/json\"),\n}\n```\n\n### Retries\n\nCertain errors will be automatically retried 2 times by default, with a short exponential backoff.\nWe retry by default all connection errors, 408 Request Timeout, 409 Conflict, 429 Rate Limit,\nand \u003e=500 Internal errors.\n\nYou can use the `WithMaxRetries` option to configure or disable this:\n\n```go\n// Configure the default for all requests:\nclient := kernel.NewClient(\n\toption.WithMaxRetries(0), // default is 2\n)\n\n// Override per-request:\nclient.Browsers.New(\n\tcontext.TODO(),\n\tkernel.BrowserNewParams{\n\t\tPersistence: kernel.BrowserPersistenceParam{\n\t\t\tID: \"browser-for-user-1234\",\n\t\t},\n\t},\n\toption.WithMaxRetries(5),\n)\n```\n\n### Accessing raw response data (e.g. response headers)\n\nYou can access the raw HTTP response data by using the `option.WithResponseInto()` request option. This is useful when\nyou need to examine response headers, status codes, or other details.\n\n```go\n// Create a variable to store the HTTP response\nvar response *http.Response\nbrowser, err := client.Browsers.New(\n\tcontext.TODO(),\n\tkernel.BrowserNewParams{\n\t\tPersistence: kernel.BrowserPersistenceParam{\n\t\t\tID: \"browser-for-user-1234\",\n\t\t},\n\t},\n\toption.WithResponseInto(\u0026response),\n)\nif err != nil {\n\t// handle error\n}\nfmt.Printf(\"%+v\\n\", browser)\n\nfmt.Printf(\"Status Code: %d\\n\", response.StatusCode)\nfmt.Printf(\"Headers: %+#v\\n\", response.Header)\n```\n\n### Making custom/undocumented requests\n\nThis library is typed for convenient access to the documented API. If you need to access undocumented\nendpoints, params, or response properties, the library can still be used.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints, you can use `client.Get`, `client.Post`, and other HTTP verbs.\n`RequestOptions` on the client, such as retries, will be respected when making these requests.\n\n```go\nvar (\n    // params can be an io.Reader, a []byte, an encoding/json serializable object,\n    // or a \"…Params\" struct defined in this library.\n    params map[string]any\n\n    // result can be an []byte, *http.Response, a encoding/json deserializable object,\n    // or a model defined in this library.\n    result *http.Response\n)\nerr := client.Post(context.Background(), \"/unspecified\", params, \u0026result)\nif err != nil {\n    …\n}\n```\n\n#### Undocumented request params\n\nTo make requests using undocumented parameters, you may use either the `option.WithQuerySet()`\nor the `option.WithJSONSet()` methods.\n\n```go\nparams := FooNewParams{\n    ID:   \"id_xxxx\",\n    Data: FooNewParamsData{\n        FirstName: kernel.String(\"John\"),\n    },\n}\nclient.Foo.New(context.Background(), params, option.WithJSONSet(\"data.last_name\", \"Doe\"))\n```\n\n#### Undocumented response properties\n\nTo access undocumented response properties, you may either access the raw JSON of the response as a string\nwith `result.JSON.RawJSON()`, or get the raw JSON of a particular field on the result with\n`result.JSON.Foo.Raw()`.\n\nAny fields that are not present on the response struct will be saved and can be accessed by `result.JSON.ExtraFields()` which returns the extra fields as a `map[string]Field`.\n\n### Middleware\n\nWe provide `option.WithMiddleware` which applies the given\nmiddleware to requests.\n\n```go\nfunc Logger(req *http.Request, next option.MiddlewareNext) (res *http.Response, err error) {\n\t// Before the request\n\tstart := time.Now()\n\tLogReq(req)\n\n\t// Forward the request to the next handler\n\tres, err = next(req)\n\n\t// Handle stuff after the request\n\tend := time.Now()\n\tLogRes(res, err, start - end)\n\n    return res, err\n}\n\nclient := kernel.NewClient(\n\toption.WithMiddleware(Logger),\n)\n```\n\nWhen multiple middlewares are provided as variadic arguments, the middlewares\nare applied left to right. If `option.WithMiddleware` is given\nmultiple times, for example first in the client then the method, the\nmiddleware in the client will run first and the middleware given in the method\nwill run next.\n\nYou may also replace the default `http.Client` with\n`option.WithHTTPClient(client)`. Only one http client is\naccepted (this overwrites any previous client) and receives requests after any\nmiddleware has been applied.\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n2. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/onkernel/kernel-go-sdk/issues) with questions, bugs, or suggestions.\n\n## Contributing\n\nSee [the contributing documentation](./CONTRIBUTING.md).\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fonkernel%2Fkernel-go-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fonkernel%2Fkernel-go-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fonkernel%2Fkernel-go-sdk/lists"}