Beispiel #1
0
// New gas Object
//
// Ex:
//  g := New()
//  g.Run()
func New(configPath ...string) *Engine {
	g := &Engine{}

	// init logger
	if _, err := os.Stat("log/system.log"); os.IsNotExist(err) {
		os.Mkdir("log", 0700)
	}

	g.Logger = logger.New("log/system.log")

	// init pool
	g.pool.New = func() interface{} {
		c := createContext(nil, g)

		return c
	}

	// load config
	g.Config = config.New(defaultConfig)
	if len(configPath) != 0 {
		for _, path := range configPath {
			g.Config.Load(path)
		}
	}

	// set router
	g.Router = newRouter(g) //&Router{g: g}

	// set default not found handler
	g.Router.SetNotFoundHandler(defaultNotFoundHandler)

	// set default panic handler
	g.Router.SetPanicHandler(defaultPanicHandler)

	// set static file path
	g.Router.StaticPath(g.Config.GetString("PubDir"))

	// add Log middleware
	// g.Router.Use(middleware.LogMiddleware)

	return g
}
Beispiel #2
0
func LogMiddleware(next gas.GasHandler) gas.GasHandler {
	return func(c *gas.Context) error {
		// req := c.Request()
		// res := c.Response()
		l := logger.New("log/logs.txt")

		remoteAddr := c.RemoteAddr().String()
		if ip := string(c.Request.Header.Peek(gas.XRealIP)); ip != "" {
			remoteAddr = ip
		} else if ip = string(c.Request.Header.Peek(gas.XForwardedFor)); ip != "" {
			remoteAddr = ip
		} else {
			remoteAddr, _, _ = net.SplitHostPort(remoteAddr)
		}

		start := time.Now()

		err := next(c)

		stop := time.Now()
		method := string(c.Method())
		path := string(c.Path())
		if path == "" {
			path = "/"
		}
		// size := c.Writer.Size()

		status := c.Response.StatusCode() //RespWriter.Status()

		// logger.Printf(format, remoteAddr, method, path, code, stop.Sub(start), size)

		logstr := "[" + start.Format("2006-01-02 15:04:05") + "][" + strconv.Itoa(status) + "][" + remoteAddr + "] " + method + " " + path + " Params: " + c.Request.PostArgs().String() + " ExecTime: " + stop.Sub(start).String()
		l.Info(logstr)

		return err
	}
}