{"id":14986625,"url":"https://github.com/hypnoglow/oas2","last_synced_at":"2025-04-11T21:31:08.968Z","repository":{"id":57490747,"uuid":"101921239","full_name":"hypnoglow/oas2","owner":"hypnoglow","description":"OpenAPI 2.0 (aka Swagger) utils for Golang.","archived":false,"fork":false,"pushed_at":"2019-03-21T15:48:13.000Z","size":224,"stargazers_count":19,"open_issues_count":2,"forks_count":5,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-04-10T01:11:36.885Z","etag":null,"topics":["go-swagger","go-toolkit","golang-middleware","golang-router","openapi","request-validation","router","swagger","swagger-spec"],"latest_commit_sha":null,"homepage":"","language":"Go","has_issues":true,"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/hypnoglow.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-08-30T19:33:58.000Z","updated_at":"2021-06-23T16:12:49.000Z","dependencies_parsed_at":"2022-08-30T03:40:26.555Z","dependency_job_id":null,"html_url":"https://github.com/hypnoglow/oas2","commit_stats":null,"previous_names":[],"tags_count":18,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hypnoglow%2Foas2","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hypnoglow%2Foas2/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hypnoglow%2Foas2/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hypnoglow%2Foas2/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hypnoglow","download_url":"https://codeload.github.com/hypnoglow/oas2/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248482920,"owners_count":21111400,"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-swagger","go-toolkit","golang-middleware","golang-router","openapi","request-validation","router","swagger","swagger-spec"],"created_at":"2024-09-24T14:13:14.878Z","updated_at":"2025-04-11T21:31:08.598Z","avatar_url":"https://github.com/hypnoglow.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# oas2\n\n[![GoDoc](https://godoc.org/github.com/hypnoglow/oas2?status.svg)](https://godoc.org/github.com/hypnoglow/oas2)\n[![CircleCI](https://circleci.com/gh/hypnoglow/oas2.svg?style=shield)](https://circleci.com/gh/hypnoglow/oas2)\n[![codecov](https://codecov.io/gh/hypnoglow/oas2/branch/master/graph/badge.svg)](https://codecov.io/gh/hypnoglow/oas2)\n[![Go Report Card](https://goreportcard.com/badge/github.com/hypnoglow/oas2)](https://goreportcard.com/report/github.com/hypnoglow/oas2)\n[![GitHub release](https://img.shields.io/github/tag/hypnoglow/oas2.svg)](https://github.com/hypnoglow/oas2/releases)\n[![License MIT](https://img.shields.io/badge/license-MIT-blue.svg?style=flat)](LICENSE)\n\n**Note that this is not stable yet. In accordance with semantic versioning, the API can change between any minor versions. Use a vendoring tool of your\npreference to lock an exact [release](https://github.com/hypnoglow/oas2/releases) version.**\n\nPackage oas2 provides utilities for building APIs using the OpenAPI 2.0 \nspecification (aka Swagger) in Go idiomatic way on top of `net/http`.\n\nYou don't need to learn any special framework or write `net/http`-incompatible\ncode - just delegate request validation, request parameters decoding\nand other routines to this library - and focus on your application logic.\n\nThis package is built on top of [OpenAPI Initiative golang toolkit](https://github.com/go-openapi).\n\n### Should I have an OpenAPI specification for my API?\n\nIf you don't have a spec for your API yet - it's definitely worth it to create \none. The specification itself provides many useful things, such as documentation,\nusage examples, and others. [Learn more](https://www.openapis.org/) about OpenAPI\nand its purposes. The great thing is that it is compatible with many tools for \ndevelopers and consumers; [Swagger Toolkit](https://swagger.io/) is the most popular\nset of utilities for OpenAPI.\n\nThis package offers an integration of the spec with your code. And tightly \ncoupling your code with the spec is a good thing - you create a strong contract\nfor API consumers, and any changes to your API will be clearly reflected in the \nspec. You will see many benefits, such as distinctly recognize the situation when\nyou need to increase the major version of your API because of incompatible changes.\n\n## Features\n\n### Router from a spec\n\nThis package provides an easy way to automatically create a router supporting\nall resources from your OpenAPI specification file. The underlying router is only\nyour choice - you can use [gorilla/mux](https://github.com/gorilla/mux), [chi](https://github.com/go-chi/chi)\nor any other.\n\nLet's dive into a simple example.\n\nGiven a spec: [petstore.yaml](_examples/petstore.yaml)\n\nFirst of all, load your spec in your app (note that though package import path ends in `oas2`, the package namespace is actually `oas`):\n\n```go\nimport \"github.com/hypnoglow/oas2\"\n\n// ...\n\n// specPath is a path to your spec file.\ndoc, _ := oas.LoadFile(specPath)\n```\n\nNext, create an [operation](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#operationObject) handler. \nLet's define a handler for `findPetsByStatus` operation:\n\n```go\ntype FindPetsByStatusHandler struct {\n\tstorage PetStorage\n}\n\nfunc (h FindPetsByStatusHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\tstatuses := req.URL.Query()[\"status\"]\n\n\tpets := h.storage.FindByStatus(statuses)\n\n\t_ = json.NewEncoder(w).Encode(pets)\n}\n```\n\n```go\nhandlers := oas.OperationHandlers{\n    \"findPetsByStatus\":    findPetsByStatus{},\n}\n```\n\nDefine what options (logger, middleware) you will use:\n\n```go\nlogger := logrus.New()\nlogger.SetLevel(logrus.DebugLevel)\nqueryValidator := oas.QueryValidator(errHandler)\n```\n\nCreate a router:\n\n```go\nrouter, _ := oas.NewRouter(\n    doc, \n    handlers, \n    oas.DebugLog(logger.Debugf), \n    oas.Use(queryValidator)\n)\n```\n\nThen you can use your `router` as an argument for `http.ListenAndServe` \nor even as a subrouter for the other router.\n\n```go\nhttp.ListenAndServe(\":8080\", router)\n``` \n\nNow the server handles requests based on the paths defined in the given spec.\nIt validates request query parameters against the spec and runs `errHandler` \nfunc if any error occured during validation. The router also sets the operation\nidentifier to each request's context, so it can be used in a handler or any custom\nmiddleware.\n\nSee the full [example](_examples/router/main.go) for the complete code.\n\n### Decode query parameters to a struct\n\nGiven request query parameters: `?name=John\u0026age=27`\n\nGiven OpenAPI v2 (swagger) spec:\n\n```yaml\n...\nparameters:\n- name: name\n  type: string\n- name: age\n  type: integer\n  format: int32\n- name: loves_apples\n  type: bool\n  default: true\n...\n```\n\nIn your Go code you create a struct:\n\n```go\ntype Member struct {\n\tName        string `oas:\"name\"`\n\tAge         int32  `oas:\"age\"`\n\tLovesApples bool   `oas:\"loves_apples\"`\n}\n```\n\nAnd populate it:\n\n```go\nvar m Member \noas.DecodeQuery(req, \u0026m)\n\nfmt.Printf(\"%#v\", m) // Member{Name:\"John\", Age:27, LovesApples:true}\n```\n\nNote that it works only with oas router, because it needs to extract operation\nspec from the request. To use custom parameters spec, use `oas.DecodeQueryParams()`.\nSee [`godoc example`](https://godoc.org/github.com/hypnoglow/oas2#example-DecodeQueryParams) for details.\n\n### Pluggable formats \u0026 validators\n\nThe specification [allows](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#data-types) to have custom formats and to validate against them.\n\nThis package provides the following custom formats and validators:\n- [`partial-time`](formats/partial_time.go)\n\nYou can also implement your custom format and validator for it, and then register it:\n```go\nvalidate.RegisterFormat(\"myformat\", \u0026MyCustomFormat{}, ValidateMyCustomFormat)\n```\n\n## License\n\n[MIT](https://github.com/hypnoglow/oas2/blob/master/LICENSE).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhypnoglow%2Foas2","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhypnoglow%2Foas2","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhypnoglow%2Foas2/lists"}