123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334 |
- package macaron
- import (
- "io"
- "log"
- "net/http"
- "os"
- "reflect"
- "strings"
- "sync"
- "github.com/Unknwon/com"
- "gopkg.in/ini.v1"
- "github.com/go-macaron/inject"
- )
- const _VERSION = "1.3.2.1216"
- func Version() string {
- return _VERSION
- }
- type Handler interface{}
- type handlerFuncInvoker func(http.ResponseWriter, *http.Request)
- func (invoke handlerFuncInvoker) Invoke(params []interface{}) ([]reflect.Value, error) {
- invoke(params[0].(http.ResponseWriter), params[1].(*http.Request))
- return nil, nil
- }
- type internalServerErrorInvoker func(rw http.ResponseWriter, err error)
- func (invoke internalServerErrorInvoker) Invoke(params []interface{}) ([]reflect.Value, error) {
- invoke(params[0].(http.ResponseWriter), params[1].(error))
- return nil, nil
- }
- func validateAndWrapHandler(h Handler) Handler {
- if reflect.TypeOf(h).Kind() != reflect.Func {
- panic("Macaron handler must be a callable function")
- }
- if !inject.IsFastInvoker(h) {
- switch v := h.(type) {
- case func(*Context):
- return ContextInvoker(v)
- case func(*Context, *log.Logger):
- return LoggerInvoker(v)
- case func(http.ResponseWriter, *http.Request):
- return handlerFuncInvoker(v)
- case func(http.ResponseWriter, error):
- return internalServerErrorInvoker(v)
- }
- }
- return h
- }
- func validateAndWrapHandlers(handlers []Handler, wrappers ...func(Handler) Handler) []Handler {
- var wrapper func(Handler) Handler
- if len(wrappers) > 0 {
- wrapper = wrappers[0]
- }
- wrappedHandlers := make([]Handler, len(handlers))
- for i, h := range handlers {
- h = validateAndWrapHandler(h)
- if wrapper != nil && !inject.IsFastInvoker(h) {
- h = wrapper(h)
- }
- wrappedHandlers[i] = h
- }
- return wrappedHandlers
- }
- type Macaron struct {
- inject.Injector
- befores []BeforeHandler
- handlers []Handler
- action Handler
- hasURLPrefix bool
- urlPrefix string
- *Router
- logger *log.Logger
- }
- func NewWithLogger(out io.Writer) *Macaron {
- m := &Macaron{
- Injector: inject.New(),
- action: func() {},
- Router: NewRouter(),
- logger: log.New(out, "[Macaron] ", 0),
- }
- m.Router.m = m
- m.Map(m.logger)
- m.Map(defaultReturnHandler())
- m.NotFound(http.NotFound)
- m.InternalServerError(func(rw http.ResponseWriter, err error) {
- http.Error(rw, err.Error(), 500)
- })
- return m
- }
- func New() *Macaron {
- return NewWithLogger(os.Stdout)
- }
- func Classic() *Macaron {
- m := New()
- m.Use(Logger())
- m.Use(Recovery())
- m.Use(Static("public"))
- return m
- }
- func (m *Macaron) Handlers(handlers ...Handler) {
- m.handlers = make([]Handler, 0)
- for _, handler := range handlers {
- m.Use(handler)
- }
- }
- func (m *Macaron) Action(handler Handler) {
- handler = validateAndWrapHandler(handler)
- m.action = handler
- }
- type BeforeHandler func(rw http.ResponseWriter, req *http.Request) bool
- func (m *Macaron) Before(handler BeforeHandler) {
- m.befores = append(m.befores, handler)
- }
- func (m *Macaron) Use(handler Handler) {
- handler = validateAndWrapHandler(handler)
- m.handlers = append(m.handlers, handler)
- }
- func (m *Macaron) createContext(rw http.ResponseWriter, req *http.Request) *Context {
- c := &Context{
- Injector: inject.New(),
- handlers: m.handlers,
- action: m.action,
- index: 0,
- Router: m.Router,
- Req: Request{req},
- Resp: NewResponseWriter(req.Method, rw),
- Render: &DummyRender{rw},
- Data: make(map[string]interface{}),
- }
- c.SetParent(m)
- c.Map(c)
- c.MapTo(c.Resp, (*http.ResponseWriter)(nil))
- c.Map(req)
- return c
- }
- func (m *Macaron) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
- if m.hasURLPrefix {
- req.URL.Path = strings.TrimPrefix(req.URL.Path, m.urlPrefix)
- }
- for _, h := range m.befores {
- if h(rw, req) {
- return
- }
- }
- m.Router.ServeHTTP(rw, req)
- }
- func GetDefaultListenInfo() (string, int) {
- host := os.Getenv("HOST")
- if len(host) == 0 {
- host = "0.0.0.0"
- }
- port := com.StrTo(os.Getenv("PORT")).MustInt()
- if port == 0 {
- port = 4000
- }
- return host, port
- }
- func (m *Macaron) Run(args ...interface{}) {
- host, port := GetDefaultListenInfo()
- if len(args) == 1 {
- switch arg := args[0].(type) {
- case string:
- host = arg
- case int:
- port = arg
- }
- } else if len(args) >= 2 {
- if arg, ok := args[0].(string); ok {
- host = arg
- }
- if arg, ok := args[1].(int); ok {
- port = arg
- }
- }
- addr := host + ":" + com.ToStr(port)
- logger := m.GetVal(reflect.TypeOf(m.logger)).Interface().(*log.Logger)
- logger.Printf("listening on %s (%s)\n", addr, safeEnv())
- logger.Fatalln(http.ListenAndServe(addr, m))
- }
- func (m *Macaron) SetURLPrefix(prefix string) {
- m.urlPrefix = prefix
- m.hasURLPrefix = len(m.urlPrefix) > 0
- }
- const (
- DEV = "development"
- PROD = "production"
- TEST = "test"
- )
- var (
-
-
- Env = DEV
- envLock sync.Mutex
-
- Root string
-
- FlashNow bool
-
- cfg *ini.File
- )
- func setENV(e string) {
- envLock.Lock()
- defer envLock.Unlock()
- if len(e) > 0 {
- Env = e
- }
- }
- func safeEnv() string {
- envLock.Lock()
- defer envLock.Unlock()
- return Env
- }
- func init() {
- setENV(os.Getenv("MACARON_ENV"))
- var err error
- Root, err = os.Getwd()
- if err != nil {
- panic("error getting work directory: " + err.Error())
- }
- }
- func SetConfig(source interface{}, others ...interface{}) (_ *ini.File, err error) {
- cfg, err = ini.Load(source, others...)
- return Config(), err
- }
- func Config() *ini.File {
- if cfg == nil {
- return ini.Empty()
- }
- return cfg
- }
|