{"id":13413659,"url":"https://github.com/dghubble/sling","last_synced_at":"2025-05-11T03:43:21.834Z","repository":{"id":29755064,"uuid":"33298728","full_name":"dghubble/sling","owner":"dghubble","description":"A Go HTTP client library for creating and sending API requests","archived":false,"fork":false,"pushed_at":"2025-05-05T13:21:37.000Z","size":146,"stargazers_count":1698,"open_issues_count":1,"forks_count":121,"subscribers_count":25,"default_branch":"main","last_synced_at":"2025-05-07T23:06:11.686Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dghubble.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGES.md","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":{"github":["dghubble"]}},"created_at":"2015-04-02T08:42:52.000Z","updated_at":"2025-05-05T20:19:49.000Z","dependencies_parsed_at":"2023-01-14T15:35:44.008Z","dependency_job_id":"14b67019-51e4-487c-965b-c12ca0b0d8f3","html_url":"https://github.com/dghubble/sling","commit_stats":{"total_commits":121,"total_committers":20,"mean_commits":6.05,"dds":0.3223140495867769,"last_synced_commit":"18af1b72bc0bd193a7f00bfd703ab8983c8fd74b"},"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dghubble%2Fsling","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dghubble%2Fsling/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dghubble%2Fsling/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dghubble%2Fsling/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dghubble","download_url":"https://codeload.github.com/dghubble/sling/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252968117,"owners_count":21833251,"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-07-30T20:01:45.676Z","updated_at":"2025-05-07T23:06:17.190Z","avatar_url":"https://github.com/dghubble.png","language":"Go","readme":"# Sling\n[![GoDoc](https://pkg.go.dev/badge/github.com/dghubble/sling.svg)](https://pkg.go.dev/github.com/dghubble/sling)\n[![Workflow](https://github.com/dghubble/sling/actions/workflows/test.yaml/badge.svg)](https://github.com/dghubble/sling/actions/workflows/test.yaml?query=branch%3Amain)\n[![Sponsors](https://img.shields.io/github/sponsors/dghubble?logo=github)](https://github.com/sponsors/dghubble)\n[![Mastodon](https://img.shields.io/badge/follow-news-6364ff?logo=mastodon)](https://fosstodon.org/@typhoon)\n\n\u003cimg align=\"right\" src=\"https://storage.googleapis.com/dghubble/small-gopher-with-sling.png\"\u003e\n\nSling is a Go HTTP client library for creating and sending API requests.\n\nSlings store HTTP Request properties to simplify sending requests and decoding responses. Check [usage](#usage) or the [examples](examples) to learn how to compose a Sling into your API client.\n\n### Features\n\n* Method Setters: Get/Post/Put/Patch/Delete/Head\n* Add or Set Request Headers\n* Base/Path: Extend a Sling for different endpoints\n* Encode structs into URL query parameters\n* Encode a form or JSON into the Request Body\n* Receive JSON success or failure responses\n\n## Install\n\n```\ngo get github.com/dghubble/sling\n```\n\n## Documentation\n\nRead [GoDoc](https://godoc.org/github.com/dghubble/sling)\n\n## Usage\n\nUse a Sling to set path, method, header, query, or body properties and create an `http.Request`.\n\n```go\ntype Params struct {\n    Count int `url:\"count,omitempty\"`\n}\nparams := \u0026Params{Count: 5}\n\nreq, err := sling.New().Get(\"https://example.com\").QueryStruct(params).Request()\nclient.Do(req)\n```\n\n### Path\n\nUse `Path` to set or extend the URL for created Requests. Extension means the path will be resolved relative to the existing URL.\n\n```go\n// creates a GET request to https://example.com/foo/bar\nreq, err := sling.New().Base(\"https://example.com/\").Path(\"foo/\").Path(\"bar\").Request()\n```\n\nUse `Get`, `Post`, `Put`, `Patch`, `Delete`, `Head`, `Options`, `Trace`, or `Connect` which are exactly the same as `Path` except they set the HTTP method too.\n\n```go\nreq, err := sling.New().Post(\"http://upload.com/gophers\")\n```\n\n### Headers\n\n`Add` or `Set` headers for requests created by a Sling.\n\n```go\ns := sling.New().Base(baseUrl).Set(\"User-Agent\", \"Gophergram API Client\")\nreq, err := s.New().Get(\"gophergram/list\").Request()\n```\n\n### Query\n\n#### QueryStruct\n\nDefine [url tagged structs](https://godoc.org/github.com/google/go-querystring/query). Use `QueryStruct` to encode a struct as query parameters on requests.\n\n```go\n// Github Issue Parameters\ntype IssueParams struct {\n    Filter    string `url:\"filter,omitempty\"`\n    State     string `url:\"state,omitempty\"`\n    Labels    string `url:\"labels,omitempty\"`\n    Sort      string `url:\"sort,omitempty\"`\n    Direction string `url:\"direction,omitempty\"`\n    Since     string `url:\"since,omitempty\"`\n}\n```\n\n```go\ngithubBase := sling.New().Base(\"https://api.github.com/\").Client(httpClient)\n\npath := fmt.Sprintf(\"repos/%s/%s/issues\", owner, repo)\nparams := \u0026IssueParams{Sort: \"updated\", State: \"open\"}\nreq, err := githubBase.New().Get(path).QueryStruct(params).Request()\n```\n\n### Body\n\n#### JSON Body\n\nDefine [JSON tagged structs](https://golang.org/pkg/encoding/json/). Use `BodyJSON` to JSON encode a struct as the Body on requests.\n\n```go\ntype IssueRequest struct {\n    Title     string   `json:\"title,omitempty\"`\n    Body      string   `json:\"body,omitempty\"`\n    Assignee  string   `json:\"assignee,omitempty\"`\n    Milestone int      `json:\"milestone,omitempty\"`\n    Labels    []string `json:\"labels,omitempty\"`\n}\n```\n\n```go\ngithubBase := sling.New().Base(\"https://api.github.com/\").Client(httpClient)\npath := fmt.Sprintf(\"repos/%s/%s/issues\", owner, repo)\n\nbody := \u0026IssueRequest{\n    Title: \"Test title\",\n    Body:  \"Some issue\",\n}\nreq, err := githubBase.New().Post(path).BodyJSON(body).Request()\n```\n\nRequests will include an `application/json` Content-Type header.\n\n#### Form Body\n\nDefine [url tagged structs](https://godoc.org/github.com/google/go-querystring/query). Use `BodyForm` to form url encode a struct as the Body on requests.\n\n```go\ntype StatusUpdateParams struct {\n    Status             string   `url:\"status,omitempty\"`\n    InReplyToStatusId  int64    `url:\"in_reply_to_status_id,omitempty\"`\n    MediaIds           []int64  `url:\"media_ids,omitempty,comma\"`\n}\n```\n\n```go\ntweetParams := \u0026StatusUpdateParams{Status: \"writing some Go\"}\nreq, err := twitterBase.New().Post(path).BodyForm(tweetParams).Request()\n```\n\nRequests will include an `application/x-www-form-urlencoded` Content-Type header.\n\n#### Plain Body\n\nUse `Body` to set a plain `io.Reader` on requests created by a Sling.\n\n```go\nbody := strings.NewReader(\"raw body\")\nreq, err := sling.New().Base(\"https://example.com\").Body(body).Request()\n```\n\nSet a content type header, if desired (e.g. `Set(\"Content-Type\", \"text/plain\")`).\n\n### Extend a Sling\n\nEach Sling creates a standard `http.Request` (e.g. with some path and query\nparams) each time `Request()` is called. You may wish to extend an existing Sling to minimize duplication (e.g. a common client or base url).\n\nEach Sling instance provides a `New()` method which creates an independent copy, so setting properties on the child won't mutate the parent Sling.\n\n```go\nconst twitterApi = \"https://api.twitter.com/1.1/\"\nbase := sling.New().Base(twitterApi).Client(authClient)\n\n// statuses/show.json Sling\ntweetShowSling := base.New().Get(\"statuses/show.json\").QueryStruct(params)\nreq, err := tweetShowSling.Request()\n\n// statuses/update.json Sling\ntweetPostSling := base.New().Post(\"statuses/update.json\").BodyForm(params)\nreq, err := tweetPostSling.Request()\n```\n\nWithout the calls to `base.New()`, `tweetShowSling` and `tweetPostSling` would reference the base Sling and POST to\n\"https://api.twitter.com/1.1/statuses/show.json/statuses/update.json\", which\nis undesired.\n\nRecap: If you wish to *extend* a Sling, create a new child copy with `New()`.\n\n### Sending\n\n#### Receive\n\nDefine a JSON struct to decode a type from 2XX success responses. Use `ReceiveSuccess(successV interface{})` to send a new Request and decode the response body into `successV` if it succeeds.\n\n```go\n// Github Issue (abbreviated)\ntype Issue struct {\n    Title  string `json:\"title\"`\n    Body   string `json:\"body\"`\n}\n```\n\n```go\nissues := new([]Issue)\nresp, err := githubBase.New().Get(path).QueryStruct(params).ReceiveSuccess(issues)\nfmt.Println(issues, resp, err)\n```\n\nMost APIs return failure responses with JSON error details. To decode these, define success and failure JSON structs. Use `Receive(successV, failureV interface{})` to send a new Request that will automatically decode the response into the `successV` for 2XX responses or into `failureV` for non-2XX responses.\n\n```go\ntype GithubError struct {\n    Message string `json:\"message\"`\n    Errors  []struct {\n        Resource string `json:\"resource\"`\n        Field    string `json:\"field\"`\n        Code     string `json:\"code\"`\n    } `json:\"errors\"`\n    DocumentationURL string `json:\"documentation_url\"`\n}\n```\n\n```go\nissues := new([]Issue)\ngithubError := new(GithubError)\nresp, err := githubBase.New().Get(path).QueryStruct(params).Receive(issues, githubError)\nfmt.Println(issues, githubError, resp, err)\n```\n\nPass a nil `successV` or `failureV` argument to skip JSON decoding into that value.\n\n### Modify a Request\n\nSling provides the raw http.Request so modifications can be made using standard net/http features. For example, in Go 1.7+ , add HTTP tracing to a request with a context:\n\n```go\nreq, err := sling.New().Get(\"https://example.com\").QueryStruct(params).Request()\n// handle error\n\ntrace := \u0026httptrace.ClientTrace{\n   DNSDone: func(dnsInfo httptrace.DNSDoneInfo) {\n      fmt.Printf(\"DNS Info: %+v\\n\", dnsInfo)\n   },\n   GotConn: func(connInfo httptrace.GotConnInfo) {\n      fmt.Printf(\"Got Conn: %+v\\n\", connInfo)\n   },\n}\n\nreq = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))\nclient.Do(req)\n```\n\n### Build an API\n\nAPIs typically define an endpoint (also called a service) for each type of resource. For example, here is a tiny Github IssueService which [lists](https://developer.github.com/v3/issues/#list-issues-for-a-repository) repository issues.\n\n```go\nconst baseURL = \"https://api.github.com/\"\n\ntype IssueService struct {\n    sling *sling.Sling\n}\n\nfunc NewIssueService(httpClient *http.Client) *IssueService {\n    return \u0026IssueService{\n        sling: sling.New().Client(httpClient).Base(baseURL),\n    }\n}\n\nfunc (s *IssueService) ListByRepo(owner, repo string, params *IssueListParams) ([]Issue, *http.Response, error) {\n    issues := new([]Issue)\n    githubError := new(GithubError)\n    path := fmt.Sprintf(\"repos/%s/%s/issues\", owner, repo)\n    resp, err := s.sling.New().Get(path).QueryStruct(params).Receive(issues, githubError)\n    if err == nil {\n        err = githubError\n    }\n    return *issues, resp, err\n}\n```\n\n## Example APIs using Sling\n\n* Digits [dghubble/go-digits](https://github.com/dghubble/go-digits)\n* GoSquared [drinkin/go-gosquared](https://github.com/drinkin/go-gosquared)\n* Kala [ajvb/kala](https://github.com/ajvb/kala)\n* Parse [fergstar/go-parse](https://github.com/fergstar/go-parse)\n* Swagger Generator [swagger-api/swagger-codegen](https://github.com/swagger-api/swagger-codegen)\n* Twitter [dghubble/go-twitter](https://github.com/dghubble/go-twitter)\n* Stacksmith [jesustinoco/go-smith](https://github.com/jesustinoco/go-smith)\n* Spotify [omegastreamtv/Spotify](https://github.com/omegastreamtv/Spotify)\n\nCreate a Pull Request to add a link to your own API.\n\n## Motivation\n\nMany client libraries follow the lead of [google/go-github](https://github.com/google/go-github) (our inspiration!), but do so by reimplementing logic common to all clients.\n\nThis project borrows and abstracts those ideas into a Sling, an agnostic component any API client can use for creating and sending requests.\n\n## Contributing\n\nSee the [Contributing Guide](https://gist.github.com/dghubble/be682c123727f70bcfe7).\n\n## License\n\n[MIT License](LICENSE)\n","funding_links":["https://github.com/sponsors/dghubble"],"categories":["网络相关库","Go","Misc","Networking","Utilities","网络","实用工具","實用工具","HTTP Clients","工具库","Programming Languages"],"sub_categories":["Http Client","HTTP Clients","Advanced Console UIs","HTTP客户端","高级控制台界面","高級控制台界面","交流","Go","\u003cspan id=\"高级控制台用户界面-advanced-console-uis\"\u003e高级控制台用户界面 Advanced Console UIs\u003c/span\u003e"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdghubble%2Fsling","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdghubble%2Fsling","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdghubble%2Fsling/lists"}