{"id":27768010,"url":"https://github.com/koddr/gosl","last_synced_at":"2025-04-29T19:58:28.769Z","repository":{"id":157006224,"uuid":"633230611","full_name":"koddr/gosl","owner":"koddr","description":"📚 The Go Snippet Library provides snippets collection for working with routine operations in your Go programs with a super user-friendly API and the most efficient performance.","archived":false,"fork":false,"pushed_at":"2025-04-17T09:39:04.000Z","size":166,"stargazers_count":22,"open_issues_count":0,"forks_count":0,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-29T19:58:08.033Z","etag":null,"topics":["go","golang","library","snippets"],"latest_commit_sha":null,"homepage":"https://github.com/koddr/gosl","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/koddr.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,"zenodo":null},"funding":{"liberapay":"koddr"}},"created_at":"2023-04-27T03:59:26.000Z","updated_at":"2025-04-17T09:39:00.000Z","dependencies_parsed_at":"2024-07-15T16:27:25.524Z","dependency_job_id":"975a997d-70d3-4909-8f8a-87610c523a47","html_url":"https://github.com/koddr/gosl","commit_stats":{"total_commits":93,"total_committers":2,"mean_commits":46.5,"dds":"0.11827956989247312","last_synced_commit":"d72b4ea49056f1b5de2fe34803fd4e9e1b07e787"},"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koddr%2Fgosl","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koddr%2Fgosl/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koddr%2Fgosl/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/koddr%2Fgosl/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/koddr","download_url":"https://codeload.github.com/koddr/gosl/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":251574671,"owners_count":21611387,"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":["go","golang","library","snippets"],"created_at":"2025-04-29T19:58:27.976Z","updated_at":"2025-04-29T19:58:28.756Z","avatar_url":"https://github.com/koddr.png","language":"Go","funding_links":["https://liberapay.com/koddr"],"categories":[],"sub_categories":[],"readme":"# gosl – The Go Snippet Library\n\n[![Go version][go_version_img]][go_dev_url]\n[![Go report][go_report_img]][go_report_url]\n![Code coverage][code_coverage_img]\n[![License][license_img]][license_url]\n\nThe **Go Snippet Library** (_or **gosl** for a short_) provides **a snippet\ncollection** for working with routine operations in your **Go** programs with\na super **user-friendly** API and the most **efficient performance** (see\nthe [benchmarks][benchmarks] section).\n\n## ⚡️ Quick start\n\nSimply add `gosl` to your project:\n\n```bash\ngo get github.com/koddr/gosl\n```\n\nAdd the needed snippet to your Go program, like this:\n\n```go\nimport \"github.com/koddr/gosl\"\n\ntype user struct {\n    ID   int    `json:\"id\"`\n    Name string `json:\"name\"`\n}\n\nfunc main() {\n    b := []byte(\"Hello, World!\")\n    \n    s, err := gosl.ToString(b) // convert byte slice to string\n    \n    // ...\n    \n    json := []byte(`{\"id\":1,\"name\":\"Viktor\"}`)\n    model := \u0026user{}\n\n    u, err := gosl.Unmarshal(json, model) // unmarshal JSON data to struct\n\n    // ...\n}\n```\n\n...or like this to have access to snippets as embedded struct:\n\n```go\nimport \"github.com/koddr/gosl\"\n\ntype App struct {\n    // ...\n    \n    utils    *gosl.Utility                         // add regular snippets\n    genUtils *gosl.GenericUtility[any, comparable] // add generic snippets\n}\n\nfunc (a *App) handleSomething() error {\n    // ...\n    \n    s, err := a.utils.ToString(b) // convert byte slice to string\n    \n    // ...\n    \n    u, err := a.genUtils.Unmarshal(json, model) // unmarshal JSON data to struct\n    \n    // ...\n}\n```\n\n## ✨ Usage\n\nBasic usage and full code examples of all functions of the `gosl` package, you\ncan find on the [pkg.go.dev][go_dev_url] page.\n\nThe package provides two categories of functions: **regular** and **universal**\nusing generics (Go 1.18+). Also, note that some features will only work\ncorrectly on Go 1.20 and above.\n\n## 🔨 Regular functions\n\nThe regular functions of the `gosl` package are aimed at solving one single\ntask with the smallest possible allocation of your machine's resources.\n\n### Concat\n\nConcatenates strings `s` to the one string:\n\n```go\ns1 := \"this \"\ns2 := \"is \"\ns3 := \"my string\"\n\ns := gosl.Concat(s1, s2, s3) // \"this is my string\"\n```\n\n### ContainsCaseInsensitive\n\nReports if string `substr` is within string `s` (case-insensitive by default):\n\n```go\ns := \"Hello, WORLD!\"\nsubstr := \"r\"\n\nb := gosl.ContainsCaseInsensitive(s, substr) // true\n```\n\n### IsFileExist\n\nReports whether a file exists on the specified `path`:\n\n```go\np := filepath.Clean(\"~/Downloads/file.csv\")\n\nb := gosl.IsFileExist(p) // true|false\n```\n\n### IsDirExist\n\nReports whether a dir exists on the specified `path`:\n\n```go\np := filepath.Clean(\"~/Downloads/my-folder\")\n\nb := gosl.IsDirExist(p) // true|false\n```\n\n### RandomString\n\nGenerates a (**really**) random string with a given size:\n\n```go\nsize := 8\n\ns, err := gosl.RandomString(size) // string, like \"34f4ey7e\"\nif err != nil {\n    log.Fatal(err)\n}\n```\n\n### RenderStyled\n\nRenders a styled string with a given `lipgloss.Style` template:\n\n```go\ntmpl := lipgloss.NewStyle().Foreground(lipgloss.Color(\"42\")).Margin(1)\n\ns := gosl.RenderStyled(\"This is a styled text\", tmpl) // styled string\n```\n\nThis function is a more comfortable wrapper for the\n[charmbracelet/lipgloss][charmbracelet_lipgloss_url] library.\n\n### ToString\n\nConverts byte slice `b` to string or error:\n\n```go\nb := []byte(\"Hello, World!\")\n\ns, err := gosl.ToString(b) // \"Hello, World!\"\nif err != nil {\n    log.Fatal(err)\n}\n```\n\n### ToBytes\n\nConverts string `s` to byte slice or error:\n\n```go\ns := \"Hello, World!\"\n\nb, err := gosl.ToBytes(s) // [48 65 6c ...]\nif err != nil {\n    log.Fatal(err)\n}\n```\n\n### ModifyByValue\n\nModify an unknown key in the given `map[string]any` by it value:\n\n```go\nm := map[string]any{\"order\": map[string]any{\"total_cost\": 100}}\nfoundValue := 100\nnewValue := 250\n\nisFound, result := gosl.ModifyByValue(m, foundValue, newValue)\n```\n\nSupports nested maps, but only if their type is `map[string]any`.\n\n## 🛠️ Universal functions\n\nThe universal (or _generic_) functions of the `gosl` package are aimed at\nsolving one\nparticular task with the smallest possible allocation of your machine's\nresources, but can be applied to a huge number of user types.\n\n\u003e 💡 Hint: enjoy the benefits of using Go 1.18+ generics today! Instead of\n\u003e writing a regular function for each of your types, just use **one generic\n\u003e function** from the list below.\n\n### Equals\n\nCompares two values of type `T`, return `true` if they are equal:\n\n```go\ns1 := \"hello\"\ns2 := \"hello\"\n\nb := gosl.Equals(s1, s2) // true\n```\n\n### NotEquals\n\nCompares two values of type `T`, return `true` if they are **not** equal:\n\n```go\ns1 := 42\ns2 := 64\n\nb := gosl.NotEquals(s1, s2) // true\n```\n\n### ContainsInSlice\n\nReports if value `v` is within slice `s`:\n\n```go\ns := []string{\"one\", \"two\", \"three\"}\nv := \"two\"\n\nb := gosl.ContainsInSlice(s, v) // true\n```\n\n### ContainsInMap\n\nReports if key `k` is within map `m`:\n\n```go\nm := map[string]int{\"one\": 1, \"two\": 2, \"three\": 3}\nk := \"two\"\n\nb := gosl.ContainsInMap(m, k) // true\n```\n\n### ParseFileToStruct\n\nParses the given file from `path` to struct `*T`.\n\nCreate structured file in any of the supported file formats (JSON, YAML, TOML,\nor HCL) with the main data to parse (for\nexample, `./config.yml`):\n\n```yaml\nhost: https://my-server.com/api/v1\nport: '3000'\n```\n\nCreate a new struct for a parsing data (for example, `server`):\n\n```go\ntype server struct {\n    Host string `koanf:\"host\"`\n    Port string `koanf:\"port\"`\n}\n```\n\nAdd to your Go program:\n\n```go\npathToFile := \"./file.yml\" // or any URL to file in the supported format\nstructToParse := \u0026server{}\n\nsrv, err := gosl.ParseFileToStruct(pathToFile, structToParse)\nif err != nil {\n    log.Fatal(err)\n}\n\n// Results:\n//  srv.Host = \"https://my-server.com/api/v1\"\n//  srv.Port = \"3000\"\n```\n\n\u003e 💡 Note: The structured file can be placed both locally (by system path)\n\u003e and accessible via HTTP (by URL).\n\nThis generic function is based on the [knadh/koanf][knadh_koanf_url] library.\n\n### ParseFileWithEnvToStruct\n\nParses the given file from `path` to struct `*T` with an (_optional_)\nenvironment variables for a secret data.\n\nSet your secret data to environment variables with a personal prefix (for\nexample, `MY_CONFIG`):\n\n```console\nexport MY_CONFIG_TOKEN=my-secret-1234567\n```\n\nCreate structured file in any of the supported file formats (JSON, YAML, TOML, or HCL) with the main data to parse (for\nexample, `./config.yml`):\n\n```yaml\nurl: https://my-server.com/api/v1\nauth_type: Bearer\ntoken: '{{ MY_CONFIG_TOKEN }}'\n```\n\nCreate a new struct for a parsing data (for example, `config`):\n\n```go\ntype config struct {\n    URL      string `koanf:\"url\"`\n    AuthType string `koanf:\"auth_type\"`\n    Token    string `koanf:\"token\"`\n}\n```\n\nAdd to your Go program:\n\n```go\npathToFile := \"./file.yml\" // or any URL to file in the supported format\nenvPrefix := \"MY_CONFIG\"   // or \"\", if you don't want to use env\nstructToParse := \u0026config{}\n\ncfg, err := gosl.ParseFileWithEnvToStruct(pathToFile, envPrefix, structToParse)\nif err != nil {\n    log.Fatal(err)\n}\n\n// Results:\n//  cfg.URL = \"https://my-server.com/api/v1\"\n//  cfg.AuthType = \"Bearer\"\n//  cfg.Token = \"my-secret-1234567\"\n```\n\n\u003e 💡 Note: The structured file can be placed both locally (by system path)\n\u003e and accessible via HTTP (by URL).\n\nThis generic function is based on the [knadh/koanf][knadh_koanf_url] library.\n\n### Marshal\n\nMarshal struct `user` to JSON data `j` (byte slice) or error:\n\n```go\ntype user struct {\nID   int    `json:\"id\"`\n    Name string `json:\"name\"`\n}\n\nu := \u0026user{}\n\nj, err := gosl.Marshal(u) // {\"id\": 0, \"name\": \"\"}\nif err != nil {\n    log.Fatal(err)\n}\n```\n\nThis generic function is a 100% compatible drop-in replacement for the standard\n[encoding/json][encoding_json_url] library.\n\n### Unmarshal\n\nUnmarshal JSON data `j` (byte slice) to struct `user` or error:\n\n```go\ntype user struct {\n    ID   int    `json:\"id\"`\n    Name string `json:\"name\"`\n}\n\nj := []byte(`{\"id\":1,\"name\":\"Viktor\"}`)\nm := \u0026user{}\n\nu, err := gosl.Unmarshal(j, m) // [id:1 name:Viktor]\nif err != nil {\n    log.Fatal(err)\n}\n```\n\nThis generic function is a 100% compatible drop-in replacement for the standard\n[encoding/json][encoding_json_url] library.\n\n## ⏱️ Benchmarks\n\nRun benchmarks on your machine by following command:\n\n```bash\ngo test -v ./... -bench . -run ^$ -benchmem\n```\n\nAnd this is my results for all functions on test stand (Apple Macbook \nAir M1, 16 Gb RAM, macOS 13.3.1):\n\n```bash\nBenchmarkEquals-8                               \t319768486\t         3.591 ns/op\t       0 B/op\t       0 allocs/op\n\nBenchmarkNotEquals-8                            \t1000000000\t         0.5136 ns/op\t       0 B/op\t       0 allocs/op\n\nBenchmarkConcat_String2-8                       \t59083364\t        19.91 ns/op\t      32 B/op\t       1 allocs/op\nBenchmarkConcat_String8-8                       \t27004447\t        44.21 ns/op\t     128 B/op\t       1 allocs/op\nBenchmarkConcat_String32-8                      \t 9373778\t       127.4 ns/op\t     448 B/op\t       1 allocs/op\n\nBenchmarkToString_HelloWorld-8                  \t100000000\t        10.56 ns/op\t      16 B/op\t       1 allocs/op\n\nBenchmarkToBytes_HelloWorld-8                   \t1000000000\t         0.6288 ns/op\t   0 B/op\t       0 allocs/op\n\nBenchmarkRandomString_Size1-8                   \t 3649489\t       328.4 ns/op\t       6 B/op\t       3 allocs/op\nBenchmarkRandomString_Size8-8                   \t 3397297\t       351.8 ns/op\t      24 B/op\t       3 allocs/op\nBenchmarkRandomString_Size64-8                  \t 2313856\t       517.9 ns/op\t     160 B/op\t       3 allocs/op\nBenchmarkRandomString_Size512-8                 \t 1425562\t       837.8 ns/op\t    1280 B/op\t       3 allocs/op\nBenchmarkRandomString_Size4096-8                \t  186254\t      6331 ns/op\t   10240 B/op\t       3 allocs/op\n\nBenchmarkMarshal_StructField_4-8                \t 8584442\t       139.9 ns/op\t      48 B/op\t       3 allocs/op\nBenchmarkMarshal_StructField_16-8               \t 2879486\t       416.6 ns/op\t     192 B/op\t       3 allocs/op\n\nBenchmarkUnmarshal_StructField_4-8              \t 6960462\t       169.3 ns/op\t      32 B/op\t       3 allocs/op\nBenchmarkUnmarshal_StructField_16-8             \t  774032\t      1534 ns/op\t     864 B/op\t      45 allocs/op\n\nBenchmarkModifyByValue-8                        \t 2824796\t       423.2 ns/op\t     704 B/op\t       6 allocs/op\n\nBenchmarkParseFileToStruct-8                    \t   39021\t     30177 ns/op\t    6184 B/op\t     109 allocs/op\n\nBenchmarkParseFileWithEnvToStruct-8             \t   28864\t     41873 ns/op\t   12232 B/op\t     219 allocs/op\n\nBenchmarkRenderStyled-8                         \t 1459971\t       821.5 ns/op\t     440 B/op\t      12 allocs/op\n\nBenchmarkContainsCaseInsensitive_HelloWorld-8   \t24856041\t        48.46 ns/op\t      16 B/op\t       1 allocs/op\nBenchmarkContainsCaseInsensitive_LoremIpsum-8   \t 1827114\t       656.4 ns/op\t     448 B/op\t       1 allocs/op\n\nBenchmarkContainsInSlice-8                      \t122999034\t         9.758 ns/op\t   0 B/op\t       0 allocs/op\n\nBenchmarkContainsInMap-8                        \t19123504\t        62.61 ns/op\t       0 B/op\t       0 allocs/op\n\nBenchmarkIsFileExist-8                          \t  395916\t      2941 ns/op\t     240 B/op\t       2 allocs/op\n\nBenchmarkIsDirExist-8                           \t  437505\t      2696 ns/op\t     224 B/op\t       2 allocs/op\n```\n\n## 💡 Motivation\n\nAs you already know from my previous projects, I take an approach to software\ndevelopment that makes **the developer's life totally easy**.\n\nWhy repeat the same snippet, for example, to translate a byte slice to a\nstring if you can add the most efficient solution to the library once and\nimport it where you need it? Exactly right! It's an unnecessary cognitive\nload for those who will read your code in the future (and for you as well).\n\nIt is for these reasons that **The Go Snippet Library** (or `gosl` for a short)\nprovides a snippet collection for working with routine operations in your Go\nprograms with a super user-friendly API and the most efficient performance.\n\n## 🏆 A win-win cooperation\n\nAnd now, I invite you to participate in this project! Let's work **together** to\ncreate the **largest** and **most useful** library of snippets for Go\nprograms on the web today.\n\n- [Issues][repo_issues_url]: ask questions and submit your features.\n- [Pull requests][repo_pull_request_url]: send your snippets or improvements\n  to the current.\n\nYour PRs \u0026 issues are welcome! Thank you 😘\n\n## ⚠️ License\n\n[`gosl`][repo_url] is free and open-source software licensed under the\n[Apache 2.0 License][license_url], created and supported with 🩵 for people\nand robots by [Vic Shóstak][author].\n\n[go_version_img]: https://img.shields.io/badge/Go-1.20+-00ADD8?style=for-the-badge\u0026logo=go\n[go_report_img]: https://img.shields.io/badge/Go_report-A+-success?style=for-the-badge\u0026logo=none\n[go_report_url]: https://goreportcard.com/report/github.com/koddr/gosl\n[go_dev_url]: https://pkg.go.dev/github.com/koddr/gosl\n[code_coverage_img]: https://img.shields.io/badge/code_coverage-93%25-success?style=for-the-badge\u0026logo=none\n[license_img]: https://img.shields.io/badge/license-Apache_2.0-red?style=for-the-badge\u0026logo=none\n[license_url]: https://github.com/koddr/gosl/blob/main/LICENSE\n[repo_url]: https://github.com/koddr/gosl\n[repo_issues_url]: https://github.com/koddr/gosl/issues\n[repo_pull_request_url]: https://github.com/koddr/gosl/pulls\n[encoding_json_url]: https://pkg.go.dev/encoding/json\n[charmbracelet_lipgloss_url]: https://github.com/charmbracelet/lipgloss\n[knadh_koanf_url]: https://github.com/knadh/koanf\n[benchmarks]: https://github.com/koddr/gosl/tree/main#%EF%B8%8F-benchmarks\n[author]: https://github.com/koddr\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkoddr%2Fgosl","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fkoddr%2Fgosl","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fkoddr%2Fgosl/lists"}