Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/nightapes/go-rest
Simple tool to generate openapi definition in go
https://github.com/nightapes/go-rest
go golang openapi rest rest-api swagger
Last synced: 4 months ago
JSON representation
Simple tool to generate openapi definition in go
- Host: GitHub
- URL: https://github.com/nightapes/go-rest
- Owner: Nightapes
- License: mit
- Created: 2021-06-03T14:34:42.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2023-05-22T08:39:42.000Z (over 1 year ago)
- Last Synced: 2024-06-20T18:13:29.392Z (8 months ago)
- Topics: go, golang, openapi, rest, rest-api, swagger
- Language: Go
- Homepage: https://nightapes.github.io/go-rest/
- Size: 54.7 KB
- Stars: 4
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# go-rest
Generate openapi definition from code.
## Usage
```go
import "github.com/Nightapes/go-rest/pkg/openapi"
``````go
package mainimport "github.com/Nightapes/go-rest/pkg/openapi"
var GetUser = &openapi.Get{
Summary: "Get User",
Description: "Get User with given ID",
OperationID: "GetMyTest",
Tags: []string{"UserService"},
Authentication: map[string][]string{"mybasic": nil, "mybearer": {"users:read"}},
Response: map[string]openapi.MethodResponse{
"200": {
Description: "The response with userID",
Value: &User{
UserID: "exampleID",
},
},
},
Headers: []openapi.Parameter{{Description: "My custom header", Name: "test-header", Required: false, Type: openapi.INTEGER}},
Path: openapi.NewPathBuilder().
Add("users").
AddParameter("userId", openapi.STRING, "UserID").
WithQueryParameter("filter", openapi.STRING, "Filter stuff", false),
HandlerFunc: func(writer http.ResponseWriter, request *http.Request) {
user := &User{UserID: "userID"}
resp, _ := json.Marshal(user)
writer.Write(resp)
},
}func main() {
api := openapi.NewOpenAPI()
api.Title = "MyAPI"
api.Get(GetUser)
...
}
```See `./example` for complete setup
## Authentication
Middleware to get authentication is available for chi `router`
```go
authMiddleware := api.ChiAuthMiddleware(func(authName string, scopes []string, r *http.Request) bool {
log.Printf("Auth check %s %s", authName, scopes)
if authName == "mybearer" {
return false
}
return true
})r := chi.NewRouter()
for _, handleConfig := range api.GetHandleFunc() {
log.Printf("Add func %s %s", handleConfig.Method, handleConfig.Path)
r.With(authMiddleware).MethodFunc(handleConfig.Method, handleConfig.Path, handleConfig.HandlerFunc)
}
```