func compareFile(pkgRealpath string) bool { if !utils.FileExists(path.Join(workPath, "routers", commentFilename)) { return true } if utils.FileExists(path.Join(workPath, lastupdateFilename)) { content, err := ioutil.ReadFile(path.Join(workPath, lastupdateFilename)) if err != nil { return true } json.Unmarshal(content, &pkgLastupdate) lastupdate, err := getpathTime(pkgRealpath) if err != nil { return true } if v, ok := pkgLastupdate[pkgRealpath]; ok { if lastupdate <= v { return false } } } return true }
// only when the Runmode is dev will generate router file in the router/auto.go from the controller // Include(&BankAccount{}, &OrderController{},&RefundController{},&ReceiptController{}) func (p *ControllerRegistor) Include(cList ...ControllerInterface) { if RunMode == "dev" { skip := make(map[string]bool, 10) for _, c := range cList { reflectVal := reflect.ValueOf(c) t := reflect.Indirect(reflectVal).Type() gopath := os.Getenv("GOPATH") if gopath == "" { panic("you are in dev mode. So please set gopath") } pkgpath := "" wgopath := filepath.SplitList(gopath) for _, wg := range wgopath { wg, _ = filepath.EvalSymlinks(filepath.Join(wg, "src", t.PkgPath())) if utils.FileExists(wg) { pkgpath = wg break } } if pkgpath != "" { if _, ok := skip[pkgpath]; !ok { skip[pkgpath] = true parserPkg(pkgpath, t.PkgPath()) } } } } for _, c := range cList { reflectVal := reflect.ValueOf(c) t := reflect.Indirect(reflectVal).Type() key := t.PkgPath() + ":" + t.Name() if comm, ok := GlobalControllerRouter[key]; ok { for _, a := range comm { p.Add(a.Router, c, strings.Join(a.AllowHTTPMethods, ",")+":"+a.Method) } } } }
func init() { // create beego application BeeApp = NewApp() workPath, _ = os.Getwd() workPath, _ = filepath.Abs(workPath) // initialize default configurations AppPath, _ = filepath.Abs(filepath.Dir(os.Args[0])) AppConfigPath = filepath.Join(AppPath, "conf", "app.conf") if workPath != AppPath { if utils.FileExists(AppConfigPath) { os.Chdir(AppPath) } else { AppConfigPath = filepath.Join(workPath, "conf", "app.conf") } } AppConfigProvider = "ini" StaticDir = make(map[string]string) StaticDir["/static"] = "static" StaticExtensionsToGzip = []string{".css", ".js"} TemplateCache = make(map[string]*template.Template) // set this to 0.0.0.0 to make this app available to externally EnableHttpListen = true //default enable http Listen HttpAddr = "" HttpPort = 8080 HttpsPort = 10443 AppName = "beego" RunMode = "dev" //default runmod AutoRender = true RecoverPanic = true ViewsPath = "views" SessionOn = false SessionProvider = "memory" SessionName = "beegosessionID" SessionGCMaxLifetime = 3600 SessionSavePath = "" SessionCookieLifeTime = 0 //set cookie default is the brower life SessionAutoSetCookie = true UseFcgi = false UseStdIo = false MaxMemory = 1 << 26 //64MB EnableGzip = false HttpServerTimeOut = 0 ErrorsShow = true XSRFKEY = "beegoxsrf" XSRFExpire = 0 TemplateLeft = "{{" TemplateRight = "}}" BeegoServerName = "beegoServer:" + VERSION EnableAdmin = false AdminHttpAddr = "127.0.0.1" AdminHttpPort = 8088 FlashName = "BEEGO_FLASH" FlashSeperator = "BEEGOFLASH" RouterCaseSensitive = true runtime.GOMAXPROCS(runtime.NumCPU()) // init BeeLogger BeeLogger = logs.NewLogger(10000) err := BeeLogger.SetLogger("console", "") if err != nil { fmt.Println("init console log error:", err) } SetLogFuncCall(true) err = ParseConfig() if err != nil && os.IsNotExist(err) { // for init if doesn't have app.conf will not panic ac := config.NewFakeConfig() AppConfig = &beegoAppConfig{ac} Warning(err) } }
// Run beego application. func (app *App) Run() { addr := HttpAddr if HttpPort != 0 { addr = fmt.Sprintf("%s:%d", HttpAddr, HttpPort) } var ( err error l net.Listener ) endRunning := make(chan bool, 1) if UseFcgi { if UseStdIo { err = fcgi.Serve(nil, app.Handlers) // standard I/O if err == nil { BeeLogger.Info("Use FCGI via standard I/O") } else { BeeLogger.Info("Cannot use FCGI via standard I/O", err) } } else { if HttpPort == 0 { // remove the Socket file before start if utils.FileExists(addr) { os.Remove(addr) } l, err = net.Listen("unix", addr) } else { l, err = net.Listen("tcp", addr) } if err != nil { BeeLogger.Critical("Listen: ", err) } err = fcgi.Serve(l, app.Handlers) } } else { if Graceful { app.Server.Addr = addr app.Server.Handler = app.Handlers app.Server.ReadTimeout = time.Duration(HttpServerTimeOut) * time.Second app.Server.WriteTimeout = time.Duration(HttpServerTimeOut) * time.Second if EnableHttpTLS { go func() { time.Sleep(20 * time.Microsecond) if HttpsPort != 0 { addr = fmt.Sprintf("%s:%d", HttpAddr, HttpsPort) app.Server.Addr = addr } server := grace.NewServer(addr, app.Handlers) server.Server = app.Server err := server.ListenAndServeTLS(HttpCertFile, HttpKeyFile) if err != nil { BeeLogger.Critical("ListenAndServeTLS: ", err, fmt.Sprintf("%d", os.Getpid())) time.Sleep(100 * time.Microsecond) endRunning <- true } }() } if EnableHttpListen { go func() { server := grace.NewServer(addr, app.Handlers) server.Server = app.Server if ListenTCP4 && HttpAddr == "" { server.Network = "tcp4" } err := server.ListenAndServe() if err != nil { BeeLogger.Critical("ListenAndServe: ", err, fmt.Sprintf("%d", os.Getpid())) time.Sleep(100 * time.Microsecond) endRunning <- true } }() } } else { app.Server.Addr = addr app.Server.Handler = app.Handlers app.Server.ReadTimeout = time.Duration(HttpServerTimeOut) * time.Second app.Server.WriteTimeout = time.Duration(HttpServerTimeOut) * time.Second if EnableHttpTLS { go func() { time.Sleep(20 * time.Microsecond) if HttpsPort != 0 { app.Server.Addr = fmt.Sprintf("%s:%d", HttpAddr, HttpsPort) } BeeLogger.Info("https server Running on %s", app.Server.Addr) err := app.Server.ListenAndServeTLS(HttpCertFile, HttpKeyFile) if err != nil { BeeLogger.Critical("ListenAndServeTLS: ", err) time.Sleep(100 * time.Microsecond) endRunning <- true } }() } if EnableHttpListen { go func() { app.Server.Addr = addr BeeLogger.Info("http server Running on %s", app.Server.Addr) if ListenTCP4 && HttpAddr == "" { ln, err := net.Listen("tcp4", app.Server.Addr) if err != nil { BeeLogger.Critical("ListenAndServe: ", err) time.Sleep(100 * time.Microsecond) endRunning <- true return } err = app.Server.Serve(ln) if err != nil { BeeLogger.Critical("ListenAndServe: ", err) time.Sleep(100 * time.Microsecond) endRunning <- true return } } else { err := app.Server.ListenAndServe() if err != nil { BeeLogger.Critical("ListenAndServe: ", err) time.Sleep(100 * time.Microsecond) endRunning <- true } } }() } } } <-endRunning }
func serverStaticRouter(ctx *context.Context) { if ctx.Input.Method() != "GET" && ctx.Input.Method() != "HEAD" { return } requestPath := path.Clean(ctx.Input.Request.URL.Path) i := 0 for prefix, staticDir := range StaticDir { if len(prefix) == 0 { continue } if requestPath == "/favicon.ico" || requestPath == "/robots.txt" { file := path.Join(staticDir, requestPath) if utils.FileExists(file) { http.ServeFile(ctx.ResponseWriter, ctx.Request, file) return } else { i++ if i == len(StaticDir) { http.NotFound(ctx.ResponseWriter, ctx.Request) return } else { continue } } } if strings.HasPrefix(requestPath, prefix) { if len(requestPath) > len(prefix) && requestPath[len(prefix)] != '/' { continue } file := path.Join(staticDir, requestPath[len(prefix):]) finfo, err := os.Stat(file) if err != nil { if RunMode == "dev" { Warn("Can't find the file:", file, err) } http.NotFound(ctx.ResponseWriter, ctx.Request) return } //if the request is dir and DirectoryIndex is false then if finfo.IsDir() { if !DirectoryIndex { exception("403", ctx) return } else if ctx.Input.Request.URL.Path[len(ctx.Input.Request.URL.Path)-1] != '/' { http.Redirect(ctx.ResponseWriter, ctx.Request, ctx.Input.Request.URL.Path+"/", 302) return } } else if strings.HasSuffix(requestPath, "/index.html") { file := path.Join(staticDir, requestPath) if utils.FileExists(file) { http.ServeFile(ctx.ResponseWriter, ctx.Request, file) return } } //This block obtained from (https://github.com/smithfox/beego) - it should probably get merged into titan-group/beego after a pull request isStaticFileToCompress := false if StaticExtensionsToGzip != nil && len(StaticExtensionsToGzip) > 0 { for _, statExtension := range StaticExtensionsToGzip { if strings.HasSuffix(strings.ToLower(file), strings.ToLower(statExtension)) { isStaticFileToCompress = true break } } } if isStaticFileToCompress { var contentEncoding string if EnableGzip { contentEncoding = getAcceptEncodingZip(ctx.Request) } memzipfile, err := openMemZipFile(file, contentEncoding) if err != nil { return } if contentEncoding == "gzip" { ctx.Output.Header("Content-Encoding", "gzip") } else if contentEncoding == "deflate" { ctx.Output.Header("Content-Encoding", "deflate") } else { ctx.Output.Header("Content-Length", strconv.FormatInt(finfo.Size(), 10)) } http.ServeContent(ctx.ResponseWriter, ctx.Request, file, finfo.ModTime(), memzipfile) } else { http.ServeFile(ctx.ResponseWriter, ctx.Request, file) } return } } }