本文整理汇总了Golang中github.com/Unknwon/macaron.Static函数的典型用法代码示例。如果您正苦于以下问题:Golang Static函数的具体用法?Golang Static怎么用?Golang Static使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Static函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: _StartMartini
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)
}
开发者ID:luckykris,项目名称:shepherd,代码行数:28,代码来源:web.go
示例2: newInstance
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
}
开发者ID:zileyuan,项目名称:hidog,代码行数:30,代码来源:main.go
示例3: main
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)
}
开发者ID:smithjm,项目名称:peekaboo,代码行数:59,代码来源:main.go
示例4: SetMiddlewares
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())
}
开发者ID:pombredanne,项目名称:wharf-1,代码行数:10,代码来源:middleware.go
示例5: newMacaron
// 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
}
开发者ID:ericcapricorn,项目名称:gogs,代码行数:56,代码来源:web.go
示例6: SetMiddlewares
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())
}
开发者ID:pombredanne,项目名称:wharf-1,代码行数:12,代码来源:middleware.go
示例7: newMacaron
// 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
}
开发者ID:fanbuchi,项目名称:gowalker,代码行数:23,代码来源:gowalker.go
示例8: newMacaron
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
}
开发者ID:trigrass2,项目名称:tech_oa,代码行数:16,代码来源:main.go
示例9: SetMiddlewares
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())
}
开发者ID:pombredanne,项目名称:wharf-1,代码行数:19,代码来源:middleware.go
示例10: SetMiddlewares
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())
}
开发者ID:liangchenye,项目名称:oct-web,代码行数:20,代码来源:middleware.go
示例11: Test_Bindata
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!")
})
}
开发者ID:macaron-contrib,项目名称:bindata,代码行数:39,代码来源:bindata_test.go
示例12: main
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))
}
开发者ID:mehulsbhatt,项目名称:cgx,代码行数:38,代码来源:cgx.go
示例13: main
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()
}
开发者ID:Zcgong,项目名称:go-rock-libraries-showcases,代码行数:36,代码来源:context.go
示例14: newMacaron
// 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
}
开发者ID:peterhadlaw,项目名称:gogs,代码行数:81,代码来源:web.go
示例15: InitApp
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
}
开发者ID:gobuild,项目名称:gobuild,代码行数:86,代码来源:main.go
示例16: daemon
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)
}
}
开发者ID:praveenscience,项目名称:kanban,代码行数:93,代码来源:daemon.go
示例17:
// +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: "",
}),
})
开发者ID:jameswei,项目名称:file-server,代码行数:30,代码来源:assets_bindata.go
示例18: main
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,
}))
//.........这里部分代码省略.........
开发者ID:bfloriang,项目名称:dock2box,代码行数:101,代码来源:main.go
示例19: main
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)
}
}
开发者ID:harryyeh,项目名称:switch,代码行数:80,代码来源:switch.go
示例20: main
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))
}
开发者ID:james2doyle,项目名称:macaron-example,代码行数:100,代码来源:main.go
注:本文中的github.com/Unknwon/macaron.Static函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论