Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/neonxp/api
Generic api functions
https://github.com/neonxp/api
Last synced: about 1 month ago
JSON representation
Generic api functions
- Host: GitHub
- URL: https://github.com/neonxp/api
- Owner: neonxp
- License: mit
- Created: 2021-12-19T17:05:01.000Z (about 3 years ago)
- Default Branch: master
- Last Pushed: 2022-01-31T10:12:51.000Z (almost 3 years ago)
- Last Synced: 2024-06-21T12:56:19.377Z (7 months ago)
- Language: Go
- Size: 10.7 KB
- Stars: 0
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# API wrapper
API handler wrapper
## Usage
### api.Wrap(handler)
Function Wrap wraps API handler and returns standard http.HandlerFunc. It encapsulate body parsing.
#### Example
```go
package mainimport (
"context"
"fmt"
"log"
"net/http""github.com/neonxp/api"
)func main() {
h := &http.Server{Addr: "0.0.0.0:3000"}
mux := http.NewServeMux()
h.Handler = mux// Here is magic!
mux.Handle("/hello", api.Wrap(handleHello))if err := h.ListenAndServe(); err != http.ErrServerClosed {
log.Fatalln(err)
}
}// Our API handler with custom request and response types
func handleHello(ctx context.Context, req *helloRequest) (*helloResponse, error) {
return &helloResponse{Message: fmt.Sprintf("Hello, %s!", req.Name)}, nil
}// Custom request type
type helloRequest struct {
Name string `json:"name"`
}// Custom response type
type helloResponse struct {
Message string `json:"message"`
}```