func init() {
	logr = logrus.New()
	//	logr.Formatter = new(logrus.JSONFormatter)

	appName = "OHACK_API"

	goji.Abandon(gmiddleware.Logger)             //Remove default logger
	goji.Abandon(gmiddleware.Recoverer)          //Remove default Recoverer
	goji.Use(middleware.RequestIDHeader)         //Add RequestIDHeader Middleware
	glogrus := glogrus.NewGlogrus(logr, appName) //Add custom logger Middleware
	goji.Use(glogrus)
	goji.Use(middleware.NewRecoverer(logr)) //Add custom recoverer

}
Beispiel #2
0
func init() {
	// 废除全部goji默认的gojimiddle
	goji.Abandon(gojimiddle.RequestID)
	goji.Abandon(gojimiddle.Logger)
	goji.Abandon(gojimiddle.Recoverer)
	goji.Abandon(gojimiddle.AutomaticOptions)

	//增加自定义的middleware
	goji.Use(EnvInit)
	goji.Use(Defer)
	goji.Use(Mime)
	goji.Use(ParseParams)

	//mime
	initMime()
}
Beispiel #3
0
func (a *App) Serve() {
	requestHandlers := &handlers.RequestHandler{
		Config:               &a.config,
		Horizon:              a.horizon,
		TransactionSubmitter: a.transactionSubmitter,
	}

	portString := fmt.Sprintf(":%d", *a.config.Port)
	flag.Set("bind", portString)

	goji.Abandon(middleware.Logger)
	goji.Use(handlers.StripTrailingSlashMiddleware())
	goji.Use(handlers.HeadersMiddleware())
	if a.config.ApiKey != "" {
		goji.Use(handlers.ApiKeyMiddleware(a.config.ApiKey))
	}

	if a.config.Accounts.AuthorizingSeed != nil {
		goji.Post("/authorize", requestHandlers.Authorize)
	} else {
		log.Warning("accounts.authorizing_seed not provided. /authorize endpoint will not be available.")
	}

	if a.config.Accounts.IssuingSeed != nil {
		goji.Post("/send", requestHandlers.Send)
	} else {
		log.Warning("accounts.issuing_seed not provided. /send endpoint will not be available.")
	}

	goji.Post("/payment", requestHandlers.Payment)
	goji.Serve()
}
Beispiel #4
0
func main() {
	flag.Parse()

	// Initialize db.
	var db db.DB
	if err := db.Open(*dbFile, 0600); err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// Initialize wiki.
	w, err := wiki.NewWiki(&db)
	if err != nil {
		log.Fatal(err)
	}

	if *loggerEnabled != true {
		goji.Abandon(middleware.Logger)
	}

	// Setup up the routes for the wiki
	goji.Get("/", w.Show)
	goji.Get("/:name", w.Show)
	goji.Get("/:name/", w.RedirectToShow)
	goji.Get("/:name/edit", w.Edit)
	goji.Post("/:name", w.Update)

	// Start the web server
	goji.Serve()
}
Beispiel #5
0
func main() {
	flag.Parse()

	if err := checkArgs(); err != nil {
		logger.Error(err.Error())
		os.Exit(1)
	}

	conf := &controllerConfig{
		enableSyncer:       *enableSyncer,
		hostCoreosPackages: *hostCoreosPackages,
		coreosPackagesPath: *coreosPackagesPath,
		corerollerURL:      *corerollerURL,
	}
	ctl, err := newController(conf)
	if err != nil {
		logger.Error(err.Error())
		os.Exit(1)
	}
	defer ctl.close()

	setupRoutes(ctl)

	if !*httpLog {
		goji.Abandon(middleware.Logger)
	}
	goji.Serve()
}
func init() {
	logr = logrus.New()
	//	logr.Formatter = new(logrus.JSONFormatter)

	appName = "bloodcare.dash"

	cookieHandler = securecookie.New(
		securecookie.GenerateRandomKey(64),
		securecookie.GenerateRandomKey(32))

	goji.Abandon(gmiddleware.Logger)             //Remove default logger
	goji.Abandon(gmiddleware.Recoverer)          //Remove default Recoverer
	goji.Use(middleware.RequestIDHeader)         //Add RequestIDHeader Middleware
	glogrus := glogrus.NewGlogrus(logr, appName) //Add custom logger Middleware
	goji.Use(glogrus)
	goji.Use(middleware.NewRecoverer(logr)) //Add custom recoverer

	initTpl()
}
Beispiel #7
0
// Serve starts the server
func (a *App) Serve() {
	portString := fmt.Sprintf(":%d", *a.config.Port)
	flag.Set("bind", portString)

	goji.Abandon(middleware.Logger)
	goji.Use(server.StripTrailingSlashMiddleware())
	goji.Use(server.HeadersMiddleware())
	if a.config.APIKey != "" {
		goji.Use(server.APIKeyMiddleware(a.config.APIKey))
	}

	if a.config.Accounts.AuthorizingSeed != "" {
		goji.Post("/authorize", a.requestHandler.Authorize)
	} else {
		log.Warning("accounts.authorizing_seed not provided. /authorize endpoint will not be available.")
	}

	goji.Post("/create-keypair", a.requestHandler.CreateKeypair)
	goji.Post("/builder", a.requestHandler.Builder)
	goji.Post("/payment", a.requestHandler.Payment)
	goji.Get("/payment", a.requestHandler.Payment)

	goji.Serve()
}
Beispiel #8
0
func setup() {
	goji.Use(ContentSecurityPolicy(CSPOptions{
		policy: Config.contentSecurityPolicy,
		frame:  Config.xFrameOptions,
	}))

	if Config.noLogs {
		goji.Abandon(middleware.Logger)
	}

	// make directories if needed
	err := os.MkdirAll(Config.filesDir, 0755)
	if err != nil {
		log.Fatal("Could not create files directory:", err)
	}

	err = os.MkdirAll(Config.metaDir, 0700)
	if err != nil {
		log.Fatal("Could not create metadata directory:", err)
	}

	// ensure siteURL ends wth '/'
	if lastChar := Config.siteURL[len(Config.siteURL)-1:]; lastChar != "/" {
		Config.siteURL = Config.siteURL + "/"
	}

	// Template setup
	p2l, err := NewPongo2TemplatesLoader()
	if err != nil {
		log.Fatal("Error: could not load templates", err)
	}
	TemplateSet := pongo2.NewSet("templates", p2l)
	TemplateSet.Globals["sitename"] = Config.siteName
	err = populateTemplatesMap(TemplateSet, Templates)
	if err != nil {
		log.Fatal("Error: could not load templates", err)
	}

	staticBox = rice.MustFindBox("static")
	timeStarted = time.Now()
	timeStartedStr = strconv.FormatInt(timeStarted.Unix(), 10)

	// Routing setup
	nameRe := regexp.MustCompile(`^/(?P<name>[a-z0-9-\.]+)$`)
	selifRe := regexp.MustCompile(`^/selif/(?P<name>[a-z0-9-\.]+)$`)
	selifIndexRe := regexp.MustCompile(`^/selif/$`)
	torrentRe := regexp.MustCompile(`^/(?P<name>[a-z0-9-\.]+)/torrent$`)

	goji.Get("/", indexHandler)
	goji.Get("/paste/", pasteHandler)
	goji.Get("/paste", http.RedirectHandler("/paste/", 301))

	if Config.remoteUploads {
		goji.Get("/upload", uploadRemote)
		goji.Get("/upload/", uploadRemote)
	}

	goji.Post("/upload", uploadPostHandler)
	goji.Post("/upload/", uploadPostHandler)
	goji.Put("/upload", uploadPutHandler)
	goji.Put("/upload/:name", uploadPutHandler)
	goji.Delete("/:name", deleteHandler)

	goji.Get("/static/*", staticHandler)
	goji.Get("/favicon.ico", staticHandler)
	goji.Get("/robots.txt", staticHandler)
	goji.Get(nameRe, fileDisplayHandler)
	goji.Get(selifRe, fileServeHandler)
	goji.Get(selifIndexRe, unauthorizedHandler)
	goji.Get(torrentRe, fileTorrentHandler)
	goji.NotFound(notFoundHandler)
}
Beispiel #9
0
func (s *Server) Init() {
	cl = make(chan bool)

	i404, err := ioutil.ReadFile("templates/static/assets/img/404.jpg")
	if err != nil {
		panic(err)
	}

	//cookie store
	s.Store = sessions.NewCookieStore([]byte(s.Config.Secret))
	s.Store.Options = &sessions.Options{
		Path:   "/",
		Domain: "",
		MaxAge: 86400 * 7,
	}

	s.Cache = NewCache(s.Config.CacheSize*1024*1024, s.Config.CacheFree*1024*1024, true)
	s.Cache.Start()

	stats = &statwrap{}

	go s.watcher()

	rc := NewReleasesController(s.DB, s.Config, s.Cache)
	lc := NewLogsController(s.DB)

	goji.Use(gzip.GzipHandler)
	goji.Use(s.ServerMiddleWare)
	goji.Use(s.AuthMiddleWare)

	goji.Get("/assets/404.jpg", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Add("content-type", "image/jpeg")
		w.Write(i404)
	})
	goji.Get("/assets/*", http.FileServer(http.Dir("templates/static")))

	goji.Get("/", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "templates/index.html")
	})
	goji.Get("/logs", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "templates/logs.html")
	})
	goji.Get("/stats", s.GetStats)
	goji.Get("/stats/free", s.Force)

	goji.Get("/db/release/:id/", rc.GetRelease)
	goji.Get("/db/release/:id/link", rc.GetReleaseLink)
	goji.Get("/db/release/:id/nzb", rc.GetReleaseNzb)
	goji.Get("/db/release/:id/image", rc.GetReleaseImage)
	goji.Get("/db/release/:id/thank", rc.ThankRelease)
	goji.Get("/db/releases/", rc.GetReleases)
	goji.Get("/db/tags/", s.GetTags)
	goji.Get("/db/logs/", lc.GetLogs)

	goji.Get("/login", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "templates/login.html")
	})
	goji.Get("/login/:key", s.Login)

	if *webdebug {
		goji.Handle("/debug/pprof/", pprof.Index)
		goji.Handle("/debug/pprof/cmdline", pprof.Cmdline)
		goji.Handle("/debug/pprof/profile", pprof.Profile)
		goji.Handle("/debug/pprof/symbol", pprof.Symbol)
		goji.Handle("/debug/pprof/block", pprof.Handler("block").ServeHTTP)
		goji.Handle("/debug/pprof/heap", pprof.Handler("heap").ServeHTTP)
		goji.Handle("/debug/pprof/goroutine", pprof.Handler("goroutine").ServeHTTP)
		goji.Handle("/debug/pprof/threadcreate", pprof.Handler("threadcreate").ServeHTTP)
	}

	goji.NotFound(NotFound)
	goji.Abandon(middleware.Logger)

	addr := fmt.Sprintf("%s:%s", s.Config.Host, s.Config.Port)
	log.WithField("tag", TAG).Infof("listening on %s", addr)

	serv = manners.NewServer()
	serv.InnerServer = http.Server{
		Addr:           addr,
		Handler:        goji.DefaultMux,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	err = serv.ListenAndServe(addr, goji.DefaultMux)
	if err != nil {
		panic(err)
	}

	log.WithField("tag", TAG).Info("closing")
}
Beispiel #10
0
func main() {
	goji.Get("/header/:header", header)
	goji.Get("/*", ping)
	goji.Abandon(middleware.Logger)
	goji.Serve()
}