Ejemplo n.º 1
0
func _StartMartini() {
	WEB.Use(macaron.Recovery())
	WEB.Use(macaron.Static("public",
		macaron.StaticOptions{
			FileSystem: bindata.Static(bindata.Options{
				Asset:      public.Asset,
				AssetDir:   public.AssetDir,
				AssetNames: public.AssetNames,
				Prefix:     "",
			}),
			SkipLogging: true,
		},
	))

	WEB.Use(macaron.Renderer(macaron.RenderOptions{
		//Directory:  "templates",                //!!when package,escape this line. Specify what path to load the templates from.
		Layout: "layout", // Specify a layout template. Layouts can call {{ yield }} to render the current template.
		//Extensions: []string{".tmpl", ".html"}, //!!when package,escape this line.  Specify extensions to load for templates.
		//Charset:    "UTF-8",                    //!!when package,escape this line.  Sets encoding for json and html content-types. Default is "UTF-8".
		TemplateFileSystem: bindata.Templates(bindata.Options{ //make templates files into bindata.
			Asset:      templates.Asset,
			AssetDir:   templates.AssetDir,
			AssetNames: templates.AssetNames,
			Prefix:     ""}),
	}))
	LoadRoute()
	WEB.Run(cfg.HOST, cfg.PORT)
}
Ejemplo n.º 2
0
func newInstance() *macaron.Macaron {
	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	m.Use(macaron.Static("static"))
	m.Use(pongo2.Pongoer(pongo2.Options{
		Directory:  "views",
		IndentJSON: macaron.Env != macaron.PROD,
		IndentXML:  macaron.Env != macaron.PROD,
	}))
	m.Use(cache.Cacher())
	m.Use(session.Sessioner())

	//DoXXX 表示GET请求;
	//OnXXX 表示POST请求;
	//AnyXXX 表示GET、POST混合请求
	m.Any("/", AnyValidate)

	m.Get("/dogs", DoDogs)
	m.Get("/pups", DoPups)
	m.Get("/about", DoAbout)
	m.Get("/comment", DoComment)
	m.Get("/signin", DoSignin)
	m.Get("/dogDetail", DoDogDetail)
	m.Get("/pupDetail", DoPupDetail)

	m.Post("/onComment", OnComment)
	m.Post("/onSignin", OnSignin)
	return m
}
Ejemplo n.º 3
0
func main() {
	// Set log options.
	log.SetOutput(os.Stderr)
	log.SetLevel(log.WarnLevel)

	// Options.
	var opts struct {
		Verbose     bool   `short:"v" long:"verbose" description:"Verbose"`
		Version     bool   `long:"version" description:"Version"`
		BindAddr    string `short:"b" long:"bind-addr" description:"Bind to address" default:"0.0.0.0"`
		Port        int    `short:"p" long:"port" description:"Port" default:"5050"`
		StaticDir   string `short:"s" long:"static-dir" description:"Static content" default:"static"`
		TemplateDir string `short:"t" long:"template-dir" description:"Templates" default:"templates"`
	}

	// Parse options.
	if _, err := flags.Parse(&opts); err != nil {
		ferr := err.(*flags.Error)
		if ferr.Type == flags.ErrHelp {
			os.Exit(0)
		} else {
			log.Fatal(err.Error())
		}
	}

	// Print version.
	if opts.Version {
		fmt.Printf("peekaboo %s\n", Version)
		os.Exit(0)
	}

	// Set verbose.
	if opts.Verbose {
		log.SetLevel(log.InfoLevel)
	}

	// Check root.
	if runtime.GOOS != "darwin" && os.Getuid() != 0 {
		log.Fatal("This application requires root privileges to run.")
	}

	info, err := hwinfo.Get()
	if err != nil {
		log.Fatal(err.Error())
	}

	log.Infof("Using static dir: %s", opts.StaticDir)
	log.Infof("Using template dir: %s", opts.TemplateDir)

	m := macaron.Classic()
	m.Use(macaron.Static(opts.StaticDir))
	m.Use(macaron.Renderer(macaron.RenderOptions{
		Directory:  opts.TemplateDir,
		IndentJSON: true,
	}))

	routes(m, info)
	m.Run(opts.BindAddr, opts.Port)
}
Ejemplo n.º 4
0
func SetMiddlewares(m *macaron.Macaron) {
	m.Use(macaron.Static("static", macaron.StaticOptions{
		Expires: func() string { return "max-age=0" },
	}))

	m.Map(Log)
	m.Use(logger())

	m.Use(macaron.Recovery())
}
Ejemplo n.º 5
0
// newMacaron initializes Macaron instance.
func newMacaron() *macaron.Macaron {
	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	if setting.EnableGzip {
		m.Use(macaron.Gziper())
	}
	m.Use(macaron.Static(
		path.Join(setting.StaticRootPath, "public"),
		macaron.StaticOptions{
			SkipLogging: !setting.DisableRouterLog,
		},
	))
	m.Use(macaron.Renderer(macaron.RenderOptions{
		Directory:  path.Join(setting.StaticRootPath, "templates"),
		Funcs:      []template.FuncMap{base.TemplateFuncs},
		IndentJSON: macaron.Env != macaron.PROD,
	}))
	m.Use(i18n.I18n(i18n.Options{
		SubURL:          setting.AppSubUrl,
		Directory:       path.Join(setting.ConfRootPath, "locale"),
		CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
		Langs:           setting.Langs,
		Names:           setting.Names,
		Redirect:        true,
	}))
	m.Use(cache.Cacher(cache.Options{
		Adapter:  setting.CacheAdapter,
		Interval: setting.CacheInternal,
		Conn:     setting.CacheConn,
	}))
	m.Use(captcha.Captchaer(captcha.Options{
		SubURL: setting.AppSubUrl,
	}))
	m.Use(session.Sessioner(session.Options{
		Provider: setting.SessionProvider,
		Config:   *setting.SessionConfig,
	}))
	m.Use(csrf.Generate(csrf.Options{
		Secret:     setting.SecretKey,
		SetCookie:  true,
		Header:     "X-Csrf-Token",
		CookiePath: setting.AppSubUrl,
	}))
	m.Use(toolbox.Toolboxer(m, toolbox.Options{
		HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
			&toolbox.HealthCheckFuncDesc{
				Desc: "Database connection",
				Func: models.Ping,
			},
		},
	}))
	m.Use(middleware.Contexter())
	return m
}
Ejemplo n.º 6
0
func SetMiddlewares(m *macaron.Macaron) {
	m.Use(macaron.Static("static", macaron.StaticOptions{
		Expires: func() string { return "max-age=0" },
	}))

	InitLog(setting.RunMode, setting.LogPath)

	m.Map(Log)
	m.Use(logger(setting.RunMode))

	m.Use(macaron.Recovery())
}
Ejemplo n.º 7
0
// newMacaron initializes Macaron instance.
func newMacaron() *macaron.Macaron {
	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	m.Use(macaron.Static("public",
		macaron.StaticOptions{
			SkipLogging: setting.ProdMode,
		},
	))
	m.Use(macaron.Static("raw",
		macaron.StaticOptions{
			Prefix:      "raw",
			SkipLogging: setting.ProdMode,
		}))
	m.Use(pongo2.Pongoer(pongo2.Options{
		IndentJSON: !setting.ProdMode,
	}))
	m.Use(i18n.I18n())
	m.Use(session.Sessioner())
	m.Use(middleware.Contexter())
	return m
}
Ejemplo n.º 8
0
func SetMiddlewares(m *macaron.Macaron) {
	//设置静态文件目录,静态文件的访问不进行日志输出
	m.Use(macaron.Static("static", macaron.StaticOptions{
		Expires: func() string { return "max-age=0" },
	}))

	//设置全局 Logger
	m.Map(Log)
	//设置 logger 的 Handler 函数,处理所有 Request 的日志输出
	m.Use(logger())

	//设置 panic 的 Recovery
	m.Use(macaron.Recovery())
}
Ejemplo n.º 9
0
func newMacaron() *macaron.Macaron {
	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	m.Use(macaron.Static("static"))
	m.Use(session.Sessioner(session.Options{
		Provider:       "mysql",
		ProviderConfig: beego.AppConfig.String("mysqlstring"),
	}))
	m.Use(middleware.Contexter())
	m.Use(pongo2.Pongoer(pongo2.Options{
		Directory: "views",
	}))
	return m

}
Ejemplo n.º 10
0
func SetMiddlewares(m *macaron.Macaron) {
	//Set static file directory,static file access without log output
	m.Use(macaron.Static("external", macaron.StaticOptions{
		Expires: func() string { return "max-age=0" },
	}))

	InitLog(setting.RunMode, setting.LogPath)

	//Set global Logger
	m.Map(Log)
	//Set logger handler function, deal with all the Request log output
	m.Use(logger(setting.RunMode))

	//Set the response header info
	m.Use(setRespHeaders())

	//Set recovery handler to returns a middleware that recovers from any panics
	m.Use(macaron.Recovery())
}
Ejemplo n.º 11
0
func SetMiddlewares(m *macaron.Macaron) {
	m.Use(macaron.Static("external", macaron.StaticOptions{
		Expires: func() string { return "max-age=0" },
	}))

	m.Map(Log)
	//modify  default template setting
	m.Use(macaron.Renderer(macaron.RenderOptions{
		Directory:       "views",
		Extensions:      []string{".tmpl", ".html"},
		Funcs:           []template.FuncMap{},
		Delims:          macaron.Delims{"<<<", ">>>"},
		Charset:         "UTF-8",
		IndentJSON:      true,
		IndentXML:       true,
		PrefixXML:       []byte("macaron"),
		HTMLContentType: "text/html",
	}))
	m.Use(macaron.Recovery())
}
Ejemplo n.º 12
0
func Test_Bindata(t *testing.T) {
	Convey("Bindata service", t, func() {
		m := macaron.New()
		m.Use(macaron.Static("",
			macaron.StaticOptions{
				SkipLogging: false,
				FileSystem: Static(Options{
					Asset:      testdata.Asset,
					AssetDir:   testdata.AssetDir,
					AssetNames: testdata.AssetNames,
					Prefix:     "",
				}),
			},
		))
		m.Use(macaron.Renderer(macaron.RenderOptions{
			TemplateFileSystem: Templates(Options{
				Asset:      testdata.Asset,
				AssetDir:   testdata.AssetDir,
				AssetNames: testdata.AssetNames,
				Prefix:     "",
			}),
		}))
		m.Get("/", func(ctx *macaron.Context) {
			ctx.HTML(200, "templates/hello", "Joe")
		})

		resp := httptest.NewRecorder()
		req, err := http.NewRequest("GET", "/static/hello.css", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)
		So(resp.Body.String(), ShouldEqual, ".hello.world {\n\tfont-size: 1px;\n}")

		resp = httptest.NewRecorder()
		req, err = http.NewRequest("GET", "/", nil)
		So(err, ShouldBeNil)
		m.ServeHTTP(resp, req)
		So(resp.Body.String(), ShouldEqual, "Hello, Joe!")
	})
}
Ejemplo n.º 13
0
func main() {
	setting.AppVer = APP_VER

	log.Info("%s %s", setting.AppName, setting.AppVer)
	log.Info("Run Mode: %s", strings.Title(macaron.Env))

	m := macaron.Classic()
	m.Use(macaron.Static(setting.ArchivePath, macaron.StaticOptions{
		Prefix: "/archive",
	}))
	m.Use(pongo2.Pongoer())
	m.Use(middleware.Contexter())

	m.Get("/", func(ctx *middleware.Context) {
		ctx.Data["Targets"] = models.Targets
		ctx.HTML(200, "home")
	})
	if setting.Webhook.Mode == "test" {
		m.Get("/hook", func(ctx *middleware.Context) {
			if err := models.Build(ctx.Query("ref")); err != nil {
				ctx.JSON(500, map[string]interface{}{
					"error": err.Error(),
				})
				return
			}

			ctx.Status(200)
		})
	} else {
		m.Post("/hook", func(ctx *middleware.Context) {

		})
	}

	listenAddr := "0.0.0.0:" + com.ToStr(setting.HTTPPort)
	log.Info("Listen on http://%s", listenAddr)
	fmt.Println(http.ListenAndServe(listenAddr, m))
}
Ejemplo n.º 14
0
func main() {
	m := macaron.Classic()

	// 服务静态文件
	m.Use(macaron.Static("public"))

	// 在同一个请求中,多个处理器之间可相互传递数据
	m.Get("/", handler1, handler2, handler3)

	// 获取请求参数
	m.Get("/q", queryHandler)

	// 获取远程 IP 地址
	m.Get("/ip", ipHandler)

	// 处理器可以让出处理权限,让之后的处理器先执行
	m.Get("/next", next1, next2, next3)

	// 设置和获取 Cookie
	m.Get("/cookie/set", setCookie)
	m.Get("/cookie/get", getCookie)

	// 响应流
	m.Get("/resp", respHandler)

	// 请求对象
	m.Get("/req", reqHandler)

	// 请求级别容错恢复
	m.Get("/panic", panicHandler)

	// 全局日志器
	m.Get("/log", logger)

	m.Run()
}
Ejemplo n.º 15
0
// newMacaron initializes Macaron instance.
func newMacaron() *macaron.Macaron {
	m := macaron.New()
	if !setting.DisableRouterLog {
		m.Use(macaron.Logger())
	}
	m.Use(macaron.Recovery())
	if setting.EnableGzip {
		m.Use(macaron.Gziper())
	}
	if setting.Protocol == setting.FCGI {
		m.SetURLPrefix(setting.AppSubUrl)
	}
	m.Use(macaron.Static(
		path.Join(setting.StaticRootPath, "public"),
		macaron.StaticOptions{
			SkipLogging: setting.DisableRouterLog,
		},
	))
	m.Use(macaron.Static(
		setting.AvatarUploadPath,
		macaron.StaticOptions{
			Prefix:      "avatars",
			SkipLogging: setting.DisableRouterLog,
		},
	))
	m.Use(macaron.Renderer(macaron.RenderOptions{
		Directory:  path.Join(setting.StaticRootPath, "templates"),
		Funcs:      []template.FuncMap{base.TemplateFuncs},
		IndentJSON: macaron.Env != macaron.PROD,
	}))

	localeNames, err := bindata.AssetDir("conf/locale")
	if err != nil {
		log.Fatal(4, "Fail to list locale files: %v", err)
	}
	localFiles := make(map[string][]byte)
	for _, name := range localeNames {
		localFiles[name] = bindata.MustAsset("conf/locale/" + name)
	}
	m.Use(i18n.I18n(i18n.Options{
		SubURL:          setting.AppSubUrl,
		Files:           localFiles,
		CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
		Langs:           setting.Langs,
		Names:           setting.Names,
		Redirect:        true,
	}))
	m.Use(cache.Cacher(cache.Options{
		Adapter:       setting.CacheAdapter,
		AdapterConfig: setting.CacheConn,
		Interval:      setting.CacheInternal,
	}))
	m.Use(captcha.Captchaer(captcha.Options{
		SubURL: setting.AppSubUrl,
	}))
	m.Use(session.Sessioner(setting.SessionConfig))
	m.Use(csrf.Csrfer(csrf.Options{
		Secret:     setting.SecretKey,
		SetCookie:  true,
		Header:     "X-Csrf-Token",
		CookiePath: setting.AppSubUrl,
	}))
	m.Use(toolbox.Toolboxer(m, toolbox.Options{
		HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
			&toolbox.HealthCheckFuncDesc{
				Desc: "Database connection",
				Func: models.Ping,
			},
		},
	}))

	// OAuth 2.
	if setting.OauthService != nil {
		for _, info := range setting.OauthService.OauthInfos {
			m.Use(oauth2.NewOAuth2Provider(info.Options, info.AuthUrl, info.TokenUrl))
		}
	}
	m.Use(middleware.Contexter())
	return m
}
Ejemplo n.º 16
0
func InitApp() *macaron.Macaron {
	app := macaron.Classic()
	app.Use(macaron.Static("public"))
	app.Use(session.Sessioner())
	app.Use(oauth2.Github(
		&goauth2.Config{
			ClientID:     os.Getenv("GITHUB_CLIENT_ID"),
			ClientSecret: os.Getenv("GITHUB_CLIENT_SECRET"),
			// https://developer.github.com/v3/oauth/#scopes
			Scopes:      []string{"user:email", "public_repo", "write:repo_hook"},
			RedirectURL: "",
		},
	))

	app.Use(macaron.Renderer(macaron.RenderOptions{
		Delims: macaron.Delims{"{[", "]}"},
	}))

	app.Get("/", routers.Homepage)
	app.Get("/build", oauth2.LoginRequired, routers.Build)
	app.Post("/stats/:org/:name/:branch/:os/:arch", routers.DownloadStats)

	app.Get("/:org/:name", func(ctx *macaron.Context, r *http.Request) {
		org := ctx.Params(":org")
		//name := ctx.Params(":name")
		if org == "js" {
			ctx.Next()
			return
		}
		ctx.Redirect(r.RequestURI+"/"+"master", 302)
	})

	// api
	app.Group("/api", func() {
		app.Get("/repos", api.RepoList)
		app.Post("/repos", api.AnonymousTriggerBuild)
		app.Any("/user/repos", oauth2.LoginRequired, middleware.UserNeeded, api.UserRepoList)
		app.Get("/recent/repos", api.RecentBuild)
		app.Post("/builds", oauth2.LoginRequired, api.TriggerBuild)

		// accept PUT(callback), POST(trigger build)
		app.Any("/repos/:id/build", oauth2.LoginRequired, middleware.UserNeeded, api.RepoBuild)
		app.Get("/user", oauth2.LoginRequired, middleware.UserNeeded, api.UserInfo)
	})

	app.Get("/explore", func(ctx *macaron.Context) {
		ctx.HTML(200, "explore", nil)
	})
	app.Get("/repos", func(ctx *macaron.Context) {
		ctx.HTML(200, "repos", nil)
	})

	app.Get("/:org/:name/:branch", func(ctx *macaron.Context, r *http.Request) {
		org := ctx.Params(":org")
		name := ctx.Params(":name")
		branch := ctx.Params(":branch")

		// Here need redis connection
		repoPath := org + "/" + name
		domain := "dn-gobuild5.qbox.me"
		buildJson := fmt.Sprintf("//%s/gorelease/%s/%s/%s/%s", domain, org, name, branch, "builds.json")

		ctx.Data["DlCount"], _ = rdx.Get("downloads:" + repoPath).Int64()
		ctx.Data["Org"] = org
		ctx.Data["Name"] = name
		ctx.Data["Branch"] = branch
		ctx.Data["BuildJSON"] = template.URL(buildJson)
		prepo := &Repo{
			Domain: domain,
			Org:    org,
			Name:   name,
			Branch: branch,
			Ext:    "",
		}
		pubs := make([]*Publish, 0)
		pubs = append(pubs, prepo.Pub("darwin", "amd64"))
		pubs = append(pubs, prepo.Pub("linux", "amd64"))
		pubs = append(pubs, prepo.Pub("linux", "386"))
		pubs = append(pubs, prepo.Pub("linux", "arm"))
		pubs = append(pubs, prepo.Pub("windows", "amd64"))
		pubs = append(pubs, prepo.Pub("windows", "386"))
		ctx.Data["Pubs"] = pubs
		ctx.HTML(200, "release")
	})
	return app
}
Ejemplo n.º 17
0
func daemon(c *cobra.Command, a []string) {
	m := macaron.New()
	setting.NewContext(c)
	err := models.NewEngine()

	m.Use(middleware.Contexter())
	m.Use(macaron.Recovery())
	m.Use(macaron.Logger())
	m.Use(macaron.Renderer(
		macaron.RenderOptions{
			Directory: "templates",
			TemplateFileSystem: bindata.Templates(bindata.Options{
				Asset:      templates.Asset,
				AssetDir:   templates.AssetDir,
				AssetNames: templates.AssetNames,
				Prefix:     "",
			}),
		},
	))
	m.Use(macaron.Static("web/images",
		macaron.StaticOptions{
			Prefix: "images",
			FileSystem: bindata.Static(bindata.Options{
				Asset:      web.Asset,
				AssetDir:   web.AssetDir,
				AssetNames: web.AssetNames,
				Prefix:     "web/images",
			}),
		},
	))
	m.Use(macaron.Static("web/template",
		macaron.StaticOptions{
			Prefix: "template",
			FileSystem: bindata.Static(bindata.Options{
				Asset:      web.Asset,
				AssetDir:   web.AssetDir,
				AssetNames: web.AssetNames,
				Prefix:     "web/template",
			}),
		},
	))

	m.Use(macaron.Static("web",
		macaron.StaticOptions{
			FileSystem: bindata.Static(bindata.Options{
				Asset:      web.Asset,
				AssetDir:   web.AssetDir,
				AssetNames: web.AssetNames,
				Prefix:     "web",
			}),
			Prefix: viper.GetString("version"),
		},
	))

	m.Get("/assets/html/user/views/oauth.html", user.OauthHandler)
	m.Combo("/api/oauth").
		Get(user.OauthUrl).
		Post(binding.Json(auth.Oauth2{}), user.OauthLogin)

	m.Post("/api/login", binding.Json(auth.SignIn{}), user.SignIn)
	m.Post("/api/register", binding.Json(auth.SignUp{}), user.SignUp)
	m.Group("/api", func() {
		m.Get("/boards", board.ListBoards)
		m.Post("/boards/configure", binding.Json(models.BoardRequest{}), board.Configure)

		m.Get("/board", board.ItemBoard)
		m.Get("/labels", board.ListLabels)
		m.Get("/cards", board.ListCards)
		m.Get("/milestones", board.ListMilestones)
		m.Get("/users", board.ListMembers)
		m.Combo("/comments").
			Get(board.ListComments).
			Post(binding.Json(models.CommentRequest{}), board.CreateComment)

		m.Combo("/card").
			Post(binding.Json(models.CardRequest{}), board.CreateCard).
			Put(binding.Json(models.CardRequest{}), board.UpdateCard).
			Delete(binding.Json(models.CardRequest{}), board.DeleteCard)

		m.Put("/card/move", binding.Json(models.CardRequest{}), board.MoveToCard)

	}, middleware.Auther())
	m.Get("/*", routers.Home)
	m.Get("/ws/", sockets.Messages(), ws.ListenAndServe)

	listen := viper.GetString("server.listen")
	log.Printf("Listen: %s", listen)
	err = http.ListenAndServe(listen, m)

	if err != nil {
		log.Fatalf("Failed to start: %s", err)
	}
}
Ejemplo n.º 18
0
// +build bindata

package modules

import (
	"github.com/Unknwon/macaron"
	"github.com/codeskyblue/file-server/public"
	"github.com/codeskyblue/file-server/templates"
	"github.com/macaron-contrib/bindata"
)

var Public = macaron.Static("public",
	macaron.StaticOptions{
		Prefix: "-",
		FileSystem: bindata.Static(bindata.Options{
			Asset:      public.Asset,
			AssetDir:   public.AssetDir,
			AssetNames: public.AssetNames,
			Prefix:     "",
		}),
	})

var Renderer = macaron.Renderer(macaron.RenderOptions{
	TemplateFileSystem: bindata.Templates(bindata.Options{
		Asset:      templates.Asset,
		AssetDir:   templates.AssetDir,
		AssetNames: templates.AssetNames,
		Prefix:     "",
	}),
})
Ejemplo n.º 19
0
func main() {
	// Set log options.
	log.SetOutput(os.Stderr)
	log.SetLevel(log.WarnLevel)

	// Options.
	var opts struct {
		Verbose      bool    `short:"v" long:"verbose" description:"Verbose"`
		Version      bool    `long:"version" description:"Version"`
		BindAddr     string  `short:"b" long:"bind-addr" description:"Bind to address" default:"0.0.0.0"`
		Port         int     `short:"p" long:"port" description:"Port" default:"5050"`
		StaticDir    string  `short:"s" long:"static-dir" description:"Static content" default:"static"`
		TemplateDir  string  `short:"t" long:"template-dir" description:"Templates" default:"templates"`
		KafkaEnabled bool    `short:"K" long:"kafka" description:"Enable Kafka message bus"`
		KafkaTopic   string  `long:"kafka-topic" description:"Kafka topic" default:"peekaboo"`
		KafkaPeers   *string `long:"kafka-peers" description:"Comma-delimited list of Kafka brokers"`
		KafkaCert    *string `long:"kafka-cert" description:"Certificate file for client authentication"`
		KafkaKey     *string `long:"kafka-key" description:"Key file for client client authentication"`
		KafkaCA      *string `long:"kafka-ca" description:"CA file for TLS client authentication"`
		KafkaVerify  bool    `long:"kafka-verify" description:"Verify SSL certificate"`
	}

	// Parse options.
	if _, err := flags.Parse(&opts); err != nil {
		ferr := err.(*flags.Error)
		if ferr.Type == flags.ErrHelp {
			os.Exit(0)
		} else {
			log.Fatal(err.Error())
		}
	}

	// Print version.
	if opts.Version {
		fmt.Printf("peekaboo %s\n", Version)
		os.Exit(0)
	}

	// Set verbose.
	if opts.Verbose {
		log.SetLevel(log.InfoLevel)
	}

	// Check root.
	if runtime.GOOS != "darwin" && os.Getuid() != 0 {
		log.Fatal("This application requires root privileges to run.")
	}

	// Get hardware info.
	info := hwinfo.NewHWInfo()
	if err := info.GetTTL(); err != nil {
		log.Fatal(err.Error())
	}

	// Produce message to Kafka bus.
	log.Infof("Produce startup event to Kafka bus with topic: %s", opts.KafkaTopic)
	if opts.KafkaEnabled {
		if opts.KafkaPeers == nil {
			log.Fatal("You need to specify Kafka Peers")
		}

		user, err := user.Current()
		if err != nil {
			log.Fatal(err.Error())
		}

		event := &Event{
			Name:      "Peekaboo startup",
			EventType: STARTED,
			Created:   time.Now().Format("20060102T150405ZB"),
			CreatedBy: CreatedBy{
				User:    user.Username,
				Service: "peekaboo",
				Host:    info.Hostname,
			},
			Descr: "Peekaboo startup event",
			Data:  info,
		}

		producer := newProducer(strings.Split(*opts.KafkaPeers, ","), opts.KafkaCert, opts.KafkaKey, opts.KafkaCA, opts.KafkaVerify)
		partition, offset, err := producer.SendMessage(&sarama.ProducerMessage{
			Topic: opts.KafkaTopic,
			Value: event,
		})
		if err != nil {
			log.Fatal(err.Error())
		}

		log.Infof("Kafka partition: %v, offset: %v", partition, offset)
	}

	log.Infof("Using static dir: %s", opts.StaticDir)
	log.Infof("Using template dir: %s", opts.TemplateDir)

	m := macaron.Classic()
	m.Use(macaron.Static(opts.StaticDir))
	m.Use(macaron.Renderer(macaron.RenderOptions{
		Directory:  opts.TemplateDir,
		IndentJSON: true,
	}))

	routes(m, info)
	m.Run(opts.BindAddr, opts.Port)
}
Ejemplo n.º 20
0
func main() {
	log.Info("%s %s", setting.AppName, APP_VER)
	log.Info("Run Mode: %s", strings.Title(macaron.Env))

	m := macaron.New()
	m.Use(macaron.Logger())
	m.Use(macaron.Recovery())
	m.Use(macaron.Static("public", macaron.StaticOptions{
		SkipLogging: true,
	}))
	m.Use(pongo2.Pongoers(pongo2.Options{
		Directory:  "templates/web",
		IndentJSON: macaron.Env != macaron.PROD,
	}, "templates/admin"))
	m.Use(i18n.I18n())
	m.Use(session.Sessioner())
	m.Use(middleware.Contexter())

	// Routes.
	m.Get("/", routers.Home)
	m.Route("/download", "GET,POST", routers.Download)
	m.Get("/favicon.ico", func(ctx *middleware.Context) {
		ctx.Redirect("/img/favicon.png")
	})
	// m.Get("/search", routers.Search)
	// m.Get("/about", routers.About)

	// Package.
	m.Get("/*", routers.Package)
	m.Get("/badge/*", routers.Badge)

	// Admin.
	m.Post("/admin/auth", admin.AuthPost)
	m.Group("/admin", func() {
		m.Get("", admin.Dashboard)

		m.Group("/packages", func() {
			m.Get("", admin.Revisions)
			m.Get("/larges", admin.LargeRevisions)
		})

		m.Group("/blocks", func() {
			m.Get("", admin.Blocks)
			m.Combo("/new").Get(admin.BlockPackage).Post(admin.BlockPackagePost)
			m.Get("/:id:int/delete", admin.UnblockPackage)

			m.Group("/rules", func() {
				m.Get("", admin.BlockRules)
				m.Combo("/new").Get(admin.NewBlockRule).Post(admin.NewBlockRulePost)
				m.Get("/:id:int/run", admin.RunRule)
				m.Get("/:id:int/delete", admin.DeleteBlockRule)
			})
		})
	}, admin.Auth)

	// API.
	m.Group("/api", func() {
		m.Group("/v1", func() {
			m.Group("", func() {
				m.Get("/download", v1.Download)
				m.Get("/revision", v1.GetRevision)
			}, v1.PackageFilter())
		})
	})

	// Robots.txt
	m.Get("/robots.txt", func() string {
		return `User-agent: *
Disallow: /api/
Disallow: /download`
	})

	m.NotFound(routers.NotFound)

	listenAddr := fmt.Sprintf("0.0.0.0:%d", setting.HttpPort)
	log.Info("Listen: http://%s", listenAddr)
	if err := http.ListenAndServe(listenAddr, m); err != nil {
		log.Fatal(4, "Fail to start server: %v", err)
	}
}
Ejemplo n.º 21
0
func main() {
	// initiate the app
	m := macaron.Classic()

	// register middleware
	m.Use(macaron.Recovery())
	m.Use(macaron.Gziper())
	m.Use(macaron.Static("public",
		macaron.StaticOptions{
			// Prefix is the optional prefix used to serve the static directory content. Default is empty string.
			Prefix: "public",
			// SkipLogging will disable [Static] log messages when a static file is served. Default is false.
			SkipLogging: true,
			// IndexFile defines which file to serve as index if it exists. Default is "index.html".
			IndexFile: "index.html",
			// Expires defines which user-defined function to use for producing a HTTP Expires Header. Default is nil.
			// https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
			Expires: func() string { return "max-age=0" },
		}))
	m.Use(session.Sessioner(session.Options{
		// Name of provider. Default is "memory".
		Provider: "memory",
		// Provider configuration, it's corresponding to provider.
		ProviderConfig: "",
		// Cookie name to save session ID. Default is "MacaronSession".
		CookieName: "MacaronSession",
		// Cookie path to store. Default is "/".
		CookiePath: "/",
		// GC interval time in seconds. Default is 3600.
		Gclifetime: 3600,
		// Max life time in seconds. Default is whatever GC interval time is.
		Maxlifetime: 3600,
		// Use HTTPS only. Default is false.
		Secure: false,
		// Cookie life time. Default is 0.
		CookieLifeTime: 0,
		// Cookie domain name. Default is empty.
		Domain: "",
		// Session ID length. Default is 16.
		IDLength: 16,
		// Configuration section name. Default is "session".
		Section: "session",
	}))
	m.Use(macaron.Renderer(macaron.RenderOptions{
		// Directory to load templates. Default is "templates".
		Directory: "templates",
		// Extensions to parse template files from. Defaults are [".tmpl", ".html"].
		Extensions: []string{".tmpl", ".html"},
		// Funcs is a slice of FuncMaps to apply to the template upon compilation. Default is [].
		Funcs: []template.FuncMap{map[string]interface{}{
			"AppName": func() string {
				return "Macaron"
			},
			"AppVer": func() string {
				return "1.0.0"
			},
		}},
		// Delims sets the action delimiters to the specified strings. Defaults are ["{{", "}}"].
		Delims: macaron.Delims{"{{", "}}"},
		// Appends the given charset to the Content-Type header. Default is "UTF-8".
		Charset: "UTF-8",
		// Outputs human readable JSON. Default is false.
		IndentJSON: true,
		// Outputs human readable XML. Default is false.
		IndentXML: true,
		// Prefixes the JSON output with the given bytes. Default is no prefix.
		// PrefixJSON: []byte("macaron"),
		// Prefixes the XML output with the given bytes. Default is no prefix.
		// PrefixXML: []byte("macaron"),
		// Allows changing of output to XHTML instead of HTML. Default is "text/html".
		HTMLContentType: "text/html",
	}))
	m.Use(cache.Cacher(cache.Options{
		// Name of adapter. Default is "memory".
		Adapter: "memory",
		// Adapter configuration, it's corresponding to adapter.
		AdapterConfig: "",
		// GC interval time in seconds. Default is 60.
		Interval: 60,
		// Configuration section name. Default is "cache".
		Section: "cache",
	}))

	// setup handlers
	m.Get("/", myHandler)
	m.Get("/welcome", myOtherHandler)
	m.Get("/query", myQueryStringHandler) // /query?name=Some+Name
	m.Get("/json", myJsonHandler)
	m.Post("/contact/submit", binding.Bind(ContactForm{}), mySubmitHandler)
	m.Get("/session", mySessionHandler)
	m.Get("/set/cookie/:value", mySetCookieHandler)
	m.Get("/get/cookie", myGetCookieHandler)
	m.Get("/database", myDatabaseHandler)
	m.Get("/database/list", myDatabaseListHandler)
	m.Get("/cache/write/:key/:value", myCacheWriteHandler)
	m.Get("/cache/read/:key", myCacheReadHandler)

	log.Println("Server is running on localhost:4000...")
	log.Println(http.ListenAndServe("0.0.0.0:4000", m))
}
func main() {
	initParse()

	err := readConfig("service.conf", &c.Config)
	if err != nil {
		glog.V(1).Infof("Read Configure file fail:%#v", err)
		return
	}

	initDB(c.Config)

	m := macaron.Classic()
	macaron.Env = macaron.PROD
	m.Use(macaron.Renderer())
	m.Use(session.Sessioner(session.Options{
		Provider:       "redis",
		ProviderConfig: "addr=127.0.0.1:6379",
	}))

	m.Use(macaron.Static("public",
		macaron.StaticOptions{
			// 请求静态资源时的 URL 前缀,默认没有前缀
			Prefix: "public",
			// 禁止记录静态资源路由日志,默认为不禁止记录
			SkipLogging: true,
			// 当请求目录时的默认索引文件,默认为 "index.html"
			IndexFile: "index.html",
			// 用于返回自定义过期响应头,不能为不设置
			// https://developers.google.com/speed/docs/insights/LeverageBrowserCaching
			Expires: func() string {
				return time.Now().Add(24 * 60 * time.Minute).UTC().Format("Mon, 02 Jan 2006 15:04:05 GMT")
			},
		}))

	m.Use(macaron.Renderer(macaron.RenderOptions{
		// 模板文件目录,默认为 "templates"
		Directory: "templates",
		// 模板文件后缀,默认为 [".tmpl", ".html"]
		Extensions: []string{".tmpl", ".html"},
		// 模板函数,默认为 []
		Funcs: []template.FuncMap{map[string]interface{}{
			"AppName": func() string {
				return "Macaron"
			},
			"AppVer": func() string {
				return "1.0.0"
			},
		}},
		// 模板语法分隔符,默认为 ["{{", "}}"]
		Delims: macaron.Delims{"{{", "}}"},
		// 追加的 Content-Type 头信息,默认为 "UTF-8"
		Charset: "UTF-8",
		// 渲染具有缩进格式的 JSON,默认为不缩进
		IndentJSON: true,
		// 渲染具有缩进格式的 XML,默认为不缩进
		IndentXML: true,
		// 渲染具有前缀的 JSON,默认为无前缀
		PrefixJSON: []byte(""),
		// 渲染具有前缀的 XML,默认为无前缀
		PrefixXML: []byte(""),
		// 允许输出格式为 XHTML 而不是 HTML,默认为 "text/html"
		HTMLContentType: "text/html",
	}))
	m.Map(x)
	m.SetDefaultCookieSecret("UYCNJSHA123JCN409")
	//	m.Post("/login",controller.Login)
	//	m.Get("/logout",controller.Logout)

	m.Group("/users", func() {
		m.Post("", binding.Bind(Customer{}), controller.PostCustomer)
		m.Get("", controller.GetCustomers)
	})

	m.Group("/goods", func() {
		m.Post("", binding.Bind(Goods{}), controller.PostGood)
		m.Get("", controller.GetGoods)
	})

	m.Group("/orders", func() {
		m.Post("/alipay", binding.Bind(Order{}), controller.PostOrder)
		m.Get("", controller.GetOrders)
	})

	m.Group("/alipay", func() {
		m.Post("/notify", controller.AlipayNotify)
		m.Get("/return", controller.AlipayReturn)
	})

	m.Run(8080)
}