Skip to content

Instantly share code, notes, and snippets.

@trajber
Last active August 29, 2015 14:02
Show Gist options
  • Save trajber/20af3356457582376c9c to your computer and use it in GitHub Desktop.
Save trajber/20af3356457582376c9c to your computer and use it in GitHub Desktop.
Exemplo handy
package main
import (
"fmt"
"github.com/trajber/handy"
"github.com/trajber/handy/interceptor"
"log"
"net/http"
"runtime"
"time"
)
func main() {
srv := handy.NewHandy()
srv.Handle("/hello/", func() handy.Handler {
return new(MyHandler)
})
log.Fatal(http.ListenAndServe(":8888", srv))
}
type Erroer interface {
SetErr(err error)
GetErr() error
}
type MyHandler struct {
handy.DefaultHandler
Response MyResponse `response:"get,put"`
Request MyRequest `request:"all"`
Error error `error`
}
func (h *MyHandler) Get(w http.ResponseWriter, r *http.Request) {
handy.Logger.Println(h.Request.Message)
h.Response.Message = "hello world"
}
func (h *MyHandler) Put(w http.ResponseWriter, r *http.Request) {
handy.Logger.Println(h.Request.Message)
h.Response.Message = "hello world"
}
func (h *MyHandler) Interceptors() handy.InterceptorChain {
return handy.NewInterceptorChain().
Chain(new(TimerInterceptor)).
Chain(interceptor.NewRequestLogger(handy.Logger)).
Chain(interceptor.NewJSONCodec(h)).
Chain(NewErrorLoggerInterceptor(h))
}
func (h *MyHandler) SetErr(err error) {
h.Error = err
}
func (h *MyHandler) GetErr() error {
return h.Error
}
type MyResponse struct {
Message string `json:"message,omitempty"`
}
type MyRequest struct {
Message string `json:"message"`
}
type TimerInterceptor struct {
Timer time.Time
}
func (i *TimerInterceptor) Before(w http.ResponseWriter, r *http.Request) {
i.Timer = time.Now()
}
func (i *TimerInterceptor) After(w http.ResponseWriter, r *http.Request) {
handy.Logger.Println("Took", time.Since(i.Timer))
}
type ErrorLoggerInterceptor struct {
interceptor.NoBeforeInterceptor
Erroer Erroer
}
func NewErrorLoggerInterceptor(err Erroer) *ErrorLoggerInterceptor {
return &ErrorLoggerInterceptor{Erroer: err}
}
func (i *ErrorLoggerInterceptor) After(w http.ResponseWriter, r *http.Request) {
if i.Erroer.GetErr() != nil {
handy.Logger.Println("Aiiii", i.Erroer.GetErr())
}
}
type MyError struct {
Code int `json:"id"`
Message string `json:"msg"`
lineNum int
file string
}
func (e *MyError) Error() string {
return fmt.Sprintf("[ERR] %s:%d: %d %s", e.file, e.lineNum, e.Code, e.Message)
}
func NewMyError(code int, msg string) *MyError {
err := new(MyError)
err.Code = code
err.Message = msg
_, file, line, ok := runtime.Caller(1)
if !ok {
file = "???"
line = 0
}
err.file = file
err.lineNum = line
return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment