Skip to content

Commit

Permalink
doc: add example to the library
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentserpoul committed Apr 8, 2022
1 parent 8b600d4 commit 4f9661d
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# httpwrapper [![Documentation](https://godoc.org/github.com/induzo/httpwrapper?status.svg)](http://godoc.org/github.com/induzo/httpwrapper) [![audit](https://github.com/induzo/httpwrapper/actions/workflows/audit.yml/badge.svg)](https://github.com/induzo/httpwrapper/actions/workflows/audit.yml) [![Go Report Card](https://goreportcard.com/badge/github.com/induzo/httpwrapper)](https://goreportcard.com/report/github.com/induzo/httpwrapper) [![Coverage Status](https://coveralls.io/repos/github/induzo/httpwrapper/badge.svg?branch=)](https://coveralls.io/github/induzo/httpwrapper?branch=main) [![Maintainability](https://api.codeclimate.com/v1/badges/163ea119e152dab7c834/maintainability)](https://codeclimate.com/github/induzo/httpwrapper/maintainability)

wrap your API to save you from boilerplate code

## Examples

See doc or example_test.go
76 changes: 76 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package httpwrapper

import (
"context"
"io"
"log"
"net/http"
"strconv"

"github.com/rs/zerolog"
)

// Wrapping a POST http handler.
func Example_post() {
zl := zerolog.New(io.Discard).With()

type postRequest struct {
Name string `json:"name"`
}

createHandler := func() TypedHandler {
return func(r *http.Request) (*Response, *ErrorResponse) {
var pr postRequest

if err := BindBody(r, &pr); err != nil {
return nil, err
}

log.Println(pr)

return &Response{
Body: pr,
HTTPStatusCode: http.StatusCreated,
}, nil
}
}

Wrapper(zl.Logger(), createHandler()).ServeHTTP(nil, nil)
}

// Wrapping a GET http handler.
func Example_get() {
zl := zerolog.New(io.Discard).With()

getter := func(ctx context.Context, key string) (string, *ErrorResponse) {
if key == "id" {
return "1", nil
}

return "", MissingParamError{Name: key}.ToErrorResponse()
}

getHandler := func(nupg NamedURLParamsGetter) TypedHandler {
return func(r *http.Request) (*Response, *ErrorResponse) {
idParam, errR := nupg(r.Context(), "id")
if errR != nil {
return nil, errR
}

id, err := strconv.ParseInt(idParam, 10, 64)
if err != nil {
return nil, ParsingParamError{
Name: "id",
Value: idParam,
}.ToErrorResponse()
}

return &Response{
Body: id,
HTTPStatusCode: http.StatusOK,
}, nil
}
}

Wrapper(zl.Logger(), getHandler(getter)).ServeHTTP(nil, nil)
}

0 comments on commit 4f9661d

Please sign in to comment.