Copy package main
import (
"encoding/json"
"fmt"
"net/http"
"github.com/alexisvisco/kcd/pkg/errors"
"github.com/alexisvisco/kcd"
"github.com/go-chi/chi"
"github.com/liip/sheriff"
)
const (
errJson = "unable to render response in json format"
errResponse = "unable to write response"
)
type SherrifGetter interface {
GetSherrifOptions() *sheriff.Options
}
type SheriffOptions struct {
SheriffOptions *sheriff.Options `json:"-"`
}
func (g SheriffOptions) GetSherrifOptions() *sheriff.Options {
return g.SheriffOptions
}
func Render(w http.ResponseWriter, _ *http.Request, response interface{}, statusCode int) error {
if response != nil {
var (
marshal []byte
err error
)
viaSheriff, ok := response.(SherrifGetter)
if ok {
// sheriff return a map[string]interface{} with keys taken from the json tag
response, err = sheriff.Marshal(viaSheriff.GetSherrifOptions(), response)
if err != nil {
return errors.Wrap(err, errJson).WithKind(errors.KindInternal)
}
}
marshal, err = json.Marshal(response)
if err != nil {
return errors.Wrap(err, errJson).WithKind(errors.KindInternal)
}
w.Header().Set("Content-type", "application/json")
w.WriteHeader(statusCode)
if _, err := w.Write(marshal); err != nil {
return errors.Wrap(err, errResponse).WithKind(errors.KindInternal)
}
} else {
w.WriteHeader(statusCode)
}
return nil
}
type Input struct {
Groups []string `query:"groups" default:"api" exploder:","`
}
type Output struct {
*SheriffOptions // pointer is required since we are using interface SherrifGetter
Name string `groups:"api"`
Email string `groups:"personal"`
SomethingElse string `groups:"api,personal"`
}
func main() {
kcd.Config.RenderHook = Render
r := chi.NewRouter()
r.Get("/", kcd.Handler(YourHttpHandler, http.StatusOK))
_ = http.ListenAndServe(":3000", r)
}
func YourHttpHandler(in *Input) (*Output, error) {
fmt.Println(len(in.Groups))
return &Output{
SheriffOptions: &SheriffOptions{SheriffOptions: &sheriff.Options{
Groups: in.Groups,
ApiVersion: nil,
}},
Name: "Alexis",
Email: "alexis.viscogliosi@outlook.fr",
SomethingElse: "haha !",
}, nil
}
// Test it : curl 'localhost:3000?groups=api'
// Test it : curl 'localhost:3000?groups=personal'
// Test it : curl 'localhost:3000?groups=personal,api'
// Test it : curl 'localhost:3000?groups='