{"id":15091226,"url":"https://github.com/huk-coburg/openapirouter","last_synced_at":"2025-08-08T04:42:03.195Z","repository":{"id":37952165,"uuid":"341830367","full_name":"HUK-COBURG/openapirouter","owner":"HUK-COBURG","description":"The OpenAPI-Router is a \"Contract-First\" http-Router for Go applications, specifically designed for JSON-based REST-Services.","archived":false,"fork":false,"pushed_at":"2023-09-07T20:29:08.000Z","size":59,"stargazers_count":13,"open_issues_count":1,"forks_count":1,"subscribers_count":8,"default_branch":"main","last_synced_at":"2025-03-26T02:03:37.803Z","etag":null,"topics":["json","open-api","rest","router"],"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/HUK-COBURG.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}},"created_at":"2021-02-24T08:28:59.000Z","updated_at":"2024-10-10T14:26:03.000Z","dependencies_parsed_at":"2023-09-24T06:57:39.806Z","dependency_job_id":"7afe5592-15a2-40e5-ae5f-d048e98f41ad","html_url":"https://github.com/HUK-COBURG/openapirouter","commit_stats":{"total_commits":41,"total_committers":8,"mean_commits":5.125,"dds":0.5853658536585367,"last_synced_commit":"beceaa0ab4ada604a6b9bc43dcee1380ae85624d"},"previous_names":[],"tags_count":8,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HUK-COBURG%2Fopenapirouter","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HUK-COBURG%2Fopenapirouter/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HUK-COBURG%2Fopenapirouter/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/HUK-COBURG%2Fopenapirouter/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/HUK-COBURG","download_url":"https://codeload.github.com/HUK-COBURG/openapirouter/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248529789,"owners_count":21119580,"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":["json","open-api","rest","router"],"created_at":"2024-09-25T10:36:34.282Z","updated_at":"2025-04-12T06:32:11.421Z","avatar_url":"https://github.com/HUK-COBURG.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"[![Go](https://github.com/HUK-COBURG/openapirouter/actions/workflows/go.yml/badge.svg)](https://github.com/HUK-COBURG/openapirouter/actions/workflows/go.yml)\n[![CodeQL](https://github.com/HUK-COBURG/openapirouter/actions/workflows/codeql-analysis.yml/badge.svg)](https://github.com/HUK-COBURG/openapirouter/actions/workflows/codeql-analysis.yml)\n[![Go Report Card](https://goreportcard.com/badge/github.com/huk-coburg/openapirouter)](https://goreportcard.com/report/github.com/huk-coburg/openapirouter)\n[![GoDoc](https://godoc.org/github.com/huk-coburg/openapirouter?status.svg)](https://godoc.org/github.com/huk-coburg/openapirouter)\n\n# OpenAPI-Router\nThe OpenAPI-Router is a \"Contract-First\" http-Router, specifically designed for JSON-based REST-Services. It takes an\n[OpenAPI schema](https://swagger.io/specification/) as input to create the router. The router validates requests and \nmaps them to their handler method using [kin-openapi](https://github.com/getkin/kin-openapi/). Additionally, the router\nsimplifies request writing and error handling for JSON-based REST-Services.\n\n## Features\n- HTTP-Router with automatic OpenAPI validation\n- Implementation `http.Handler` to be compatible with existing HTTP libraries\n- Automatic response writing of JSON or plain-text responses\n- ErrorMapper to write helpful responses based on the type of error\n\n## How to use\n### Installation\n```shell\ngo get github.com/huk-coburg/openapirouter\n```\n\n### Creating the router\nIn order to create the router, a file with the OpenAPI specification is needed. The file can be in JSON or YAML format.\nThe router is created using the following `NewRouter` function with the path of the OpenAPI file.\n\n### Handler function\nTo enable the automatic response writing and error mapping, a custom handler function different from the standard \n`http.HandlerFunc` is used for the implementation of endpoints. The following function signature is used:  \n```go\nfunc(request *http.Request, pathParamerters map[string]string) (*openapirouter.Response, error)\n```  \nThe parameters are:\n- **request:** The pointer to the http.Request as in the standard `http.HandlerFunc`. It can be used to extract the \n  request body, the headers or query parameters.\n- **pathParameters:** A map of the path parameters which are extracted for validation and are populated to the request,\n  so they don't need to be extracted manually for the URL.\n- **Response:** A struct to depict the response to be returned. It is used to set the response body, the status and the \n  response headers.\n- **error:** Standard Go error to indicate that an error occurred.\n\nThe `AddRequestHandler` function of the router is used to add a function for a specific path and method to the router.\n\nIf an endpoint defines a security requirement, `AddRequestHandlerWithAuthFunc` must be used in order to enable the \nrouter to check if the user is authorized to access the endpoint. Using the `openapi3filter.NoopAuthenticationFunc` \nas `authFunc` will grant access for any request without further checks. \n\n### Error handling\nIf the handler function returns an error, it will be mapped to a corresponding response. Therefore, a custom `HTTPError`\nis used and returned as a JSON response. It contains the following fields:\n```go\ntype HTTPError struct {\n\t// HTTP status code to return\n\tStatusCode int\n\t// URL to describe the response code\n\tType       string\n\t// name of the response\n\tTitle      string\n\t// additional details for the error, e.g. what went wrong\n\tDetails    []string  \n}\n```  \nIf an `HTTPError` is returned by the handler function, it will be mapped to a corresponding response by default. The \n`NewError` function is used to create such an error for a status code with any number of details.\n\nIt is also possible to map any other error produced by the handler function to a response. Unknown errors are mapped to \nan `Internal Server Error` by default. In order to create a different response, the error needs to be added to the \nrouters' error mapper by using the `AddErrorMapping` function to define the `HTTPError` it should be mapped to.\n\n### Full Example\n\n```go\npackage main\n\nimport (\n\t\"github.com/huk-coburg/openapirouter\"\n\t\"net/http\"\n)\n\n// Struct for the data to be returned\ntype MyOutputData struct {\n\tData string `json:\"data\"`\n}\n\n// Custom error to be mapped by error mapper\ntype MyCustomError struct {\n}\n\nfunc (e *MyCustomError) Error() string {\n\treturn \"oops\"\n}\n\n// Example function which can produce an error\nfunc GetDataForClient(client string) (*MyOutputData, error) {\n\tvar data *MyOutputData\n\tvar success bool\n\t// ...\n\tif success {\n\t\treturn data, nil\n\t} else {\n\t\treturn nil, \u0026MyCustomError{}\n\t}\n}\n\n// HandlerFunction to assign to an endpoint\nfunc HandleRequest(_ *http.Request, pathParams map[string]string) (*openapirouter.Response, error) {\n\t// Extract path parameter\n\tclient := pathParams[\"client\"]\n\tif client == \"unknown\" {\n\t\t// Return HttpError which is mapped automatically\n\t\treturn nil, openapirouter.NewHTTPError(http.StatusForbidden, \"unknown client must not receive data\")\n\t}\n\tdata, err := GetDataForClient(client)\n\tif err != nil {\n\t\t// Return custom error to be mapped\n\t\treturn nil, err\n\t}\n\t// Return response to be written\n\treturn \u0026openapirouter.Response{\n\t\tStatusCode: http.StatusOK,\n\t\tBody:       data,\n\t}, nil\n\n}\n\nfunc main() {\n\trouter, err := openapirouter.NewRouter(\"./test-api.yaml\")\n\tif err != nil {\n\t\t// Could not read file\n\t\tpanic(err)\n\t}\n\t// Add implementation for endpoint specified in OpenAPI specification\n\t// Use router.AddRequestHandlerWithAuthFunc if the endpoint defines security requirements\n\trouter.AddRequestHandler(http.MethodGet, \"/test/{client}\", HandleRequest)\n\t// Add error mapping for MyCustomError\n\trouter.AddErrorMapping(\u0026MyCustomError{}, http.StatusBadGateway, \"could not load data\")\n\t// use router\n\t_ = http.ListenAndServe(\":8080\", router)\n}\n```\n\n## Contribute\nContributions are welcome. You can:\n- Submit bugs and feature requests as issues\n- Review code and let us know what we can do better\n- Submit PullRequests for code or documentation changes or additions\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuk-coburg%2Fopenapirouter","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhuk-coburg%2Fopenapirouter","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhuk-coburg%2Fopenapirouter/lists"}