func main() {
	//Profiling
	// go func() {
	// 	log.Println(http.ListenAndServe(":6060", nil))
	// }()

	var (
		config *app.Config
	)

	envParser := env_parser.NewEnvParser()
	envParser.Name(appName)
	envParser.Separator("_")
	envSrc := app.Envs{}
	envParseError := envParser.Map(&envSrc)
	app.Chk(envParseError)

	app.PrintWelcome()

	switch envSrc.Mode {
	case app.MODE_DEV:
		logr.Level = logrus.InfoLevel
	case app.MODE_PROD:
		logr.Level = logrus.WarnLevel
	case app.MODE_DEBUG:
		logr.Level = logrus.DebugLevel
	}

	config = app.NewConfig(envSrc.AssetsUrl, envSrc.UploadPath)

	logFile, fileError := os.OpenFile(envSrc.LogPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0660)
	defer logFile.Close()
	if fileError == nil {
		logr.Out = logFile
	} else {
		fmt.Println("invalid log file; \n, Error : ", fileError, "\nopting standard output..")
	}

	redisService, reErr := services.NewRedis(envSrc.RedisUrl)
	reErr = reErr

	sqlConnectionStringFormat := "%s:%s@tcp(%s:%s)/%s"
	sqlConnectionString := fmt.Sprintf(sqlConnectionStringFormat, envSrc.MysqlUser, envSrc.MysqlPassword,
		envSrc.MysqlHost, envSrc.MysqlPort, envSrc.MysqlDbName)
	mySqlService := services.NewMySQL(sqlConnectionString, 10)

	//TODO check
	baseHandler := handlers.NewBaseHandler(logr, config)
	userHandler := handlers.NewUserHandler(baseHandler, redisService, mySqlService)
	reqHandler := handlers.NewRequestHandler(baseHandler, redisService, mySqlService)

	goji.Post("/register", baseHandler.Route(userHandler.DoRegistration))
	goji.Post("/login", baseHandler.Route(userHandler.DoLogin))
	goji.Get("/bloodReq", baseHandler.Route(reqHandler.RemoveBloodRequest))
	goji.Post("/bloodReq", baseHandler.Route(reqHandler.MakeBloodRequest))
	goji.Delete("/bloodReq", baseHandler.Route(reqHandler.RemoveBloodRequest))
	goji.NotFound(baseHandler.NotFound)

	goji.Serve()
}
func main() {
	http.HandleFunc(template.STATIC_URL, template.StaticHandler)
	goji.Get("/", Home)
	goji.Get("/about", About)
	goji.NotFound(NotFound)

	goji.Serve()
}
Beispiel #3
0
func main() {
	goji.Use(config)
	goji.Use(database)
	goji.Get("/", handlers.Root)
	goji.Get("/authorize", handlers.Authorize)
	goji.Get("/connected", handlers.Connected)
	goji.Get("/callback", handlers.Callback)
	goji.Post("/subscriber", handlers.Subscriber)
	goji.NotFound(handlers.NotFound)
	goji.Serve()
}
Beispiel #4
0
func main() {
	// Add routes to the global handler
	goji.Get("/", Root)
	// Fully backwards compatible with net/http's Handlers
	goji.Get("/greets", http.RedirectHandler("/", 301))
	// Use your favorite HTTP verbs
	goji.Post("/greets", NewGreet)
	// Use Sinatra-style patterns in your URLs
	goji.Get("/users/:name", GetUser)
	// Goji also supports regular expressions with named capture groups.
	goji.Get(regexp.MustCompile(`^/greets/(?P<id>\d+)$`), GetGreet)

	// Middleware can be used to inject behavior into your app. The
	// middleware for this application are defined in middleware.go, but you
	// can put them wherever you like.
	goji.Use(PlainText)

	// If the patterns ends with "/*", the path is treated as a prefix, and
	// can be used to implement sub-routes.
	admin := web.New()
	goji.Handle("/admin/*", admin)

	// The standard SubRouter middleware helps make writing sub-routers
	// easy. Ordinarily, Goji does not manipulate the request's URL.Path,
	// meaning you'd have to repeat "/admin/" in each of the following
	// routes. This middleware allows you to cut down on the repetition by
	// eliminating the shared, already-matched prefix.
	admin.Use(middleware.SubRouter)
	// You can also easily attach extra middleware to sub-routers that are
	// not present on the parent router. This one, for instance, presents a
	// password prompt to users of the admin endpoints.
	admin.Use(SuperSecure)

	admin.Get("/", AdminRoot)
	admin.Get("/finances", AdminFinances)

	// Goji's routing, like Sinatra's, is exact: no effort is made to
	// normalize trailing slashes.
	goji.Get("/admin", http.RedirectHandler("/admin/", 301))

	// Use a custom 404 handler
	goji.NotFound(NotFound)

	// Sometimes requests take a long time.
	goji.Get("/waitforit", WaitForIt)

	// Call Serve() at the bottom of your main() function, and it'll take
	// care of everything else for you, including binding to a socket (with
	// automatic support for systemd and Einhorn) and supporting graceful
	// shutdown on SIGINT. Serve() is appropriate for both development and
	// production.
	goji.Serve()
}
Beispiel #5
0
func main() {
	goji.Get("/", index)
	goji.Get("/assets/*", http.FileServer(http.Dir("./dist")))
	goji.Get("/api/todos", todos)
	goji.Post("/api/todos", newTodo)
	goji.Put("/api/todos/:id", putTodo)
	goji.Delete("/api/todos/:id", delTodo)

	goji.NotFound(index)

	goji.Serve()
}
Beispiel #6
0
func StartServer(blog *Blog) {
	// Routes
	goji.Get("/", IndexHandler)
	goji.Get("/articles", AllArticlesHandler)
	goji.Get("/article/:id", ArticleHandler)
	goji.Get("/:page", PageHandler)

	goji.Get("/assets/*", http.FileServer(http.Dir("public")))
	goji.NotFound(NotFoundHandler)

	// Start Goji
	goji.Serve()
}
Beispiel #7
0
func main() {
	// Add routes to the global handler
	goji.Get("/", Root)
	// Fully backwards compatible with net/http's Handlers
	goji.Get("/greets", http.RedirectHandler("/", 301))
	// Use your favorite HTTP verbs
	goji.Post("/greets", NewGreet)
	// Use Sinatra-style patterns in your URLs
	goji.Get("/users/:name", GetUser)
	// Goji also supports regular expressions with named capture groups.
	goji.Get(regexp.MustCompile(`^/greets/(?P<id>\d+)$`), GetGreet)

	// Middleware can be used to inject behavior into your app. The
	// middleware for this application are defined in middleware.go, but you
	// can put them wherever you like.
	goji.Use(PlainText)

	// If the last character of a pattern is an asterisk, the path is
	// treated as a prefix, and can be used to implement sub-routes.
	// Sub-routes can be used to set custom middleware on sub-applications.
	// Goji's interfaces are completely composable.
	admin := web.New()
	goji.Handle("/admin/*", admin)
	admin.Use(SuperSecure)

	// Goji's routing, like Sinatra's, is exact: no effort is made to
	// normalize trailing slashes.
	goji.Get("/admin", http.RedirectHandler("/admin/", 301))

	// Set up admin routes. Note that sub-routes do *not* mutate the path in
	// any way, so we need to supply full ("/admin/" prefixed) paths.
	admin.Get("/admin/", AdminRoot)
	admin.Get("/admin/finances", AdminFinances)

	// Use a custom 404 handler
	goji.NotFound(NotFound)

	// Sometimes requests take a long time.
	goji.Get("/waitforit", WaitForIt)

	// Call Serve() at the bottom of your main() function, and it'll take
	// care of everything else for you, including binding to a socket (with
	// automatic support for systemd and Einhorn) and supporting graceful
	// shutdown on SIGINT. Serve() is appropriate for both development and
	// production.
	goji.Serve()
}
Beispiel #8
0
func main() {
	/* -- Router -- */
	// Top
	goji.Get("/", Root)

	// User list
	goji.Get("/user_list/:offset/:limit", UserList)

	// Comment List
	goji.Get("/comment_list/:offset/:limit", CommentList)

	// Comment
	goji.Post("/coment", Comment)

	goji.NotFound(NotFound)
	goji.Serve()
}
func main() {
	//Profiling
	// go func() {
	// 	log.Println(http.ListenAndServe(":6060", nil))
	// }()

	var (
		mode      string
		mysqlHost string
		redisHost string
		assetsUrl string
		config    *app.Config
		errors    []string
	)
	flag.StringVar(&mode, "mode", "dev", "dev|debug|prod")
	flag.StringVar(&assetsUrl, "assets-url", "", "http://static.assets.url")
	flag.StringVar(&mysqlHost, "mysql-host", "", "mysql.host")
	flag.StringVar(&redisHost, "redis-host", "", "redis.host")
	app.EnvParse(appName)

	if assetsUrl == "" {
		errors = append(errors, "assets-url")
	}
	if mysqlHost == "" {
		errors = append(errors, "mysql-host")
	}
	if redisHost == "" {
		errors = append(errors, "redis-host")
	}

	app.PrintWelcome()
	app.ParseErrors(errors)

	logr.Level = app.GetLogrMode(mode)
	config = app.NewConfig(assetsUrl)
	mysql := services.NewMySQL(mysqlHost, 100)

	bH := handlers.NewBaseHandler(logr, config, templates, cookieHandler)

	adminH := handlers.NewAdminHandler(bH, mysql)
	dashH := handlers.NewDashboardHandler(bH, mysql)
	bloodbankH := handlers.NewBloodBankHandler(bH, mysql)
	donorsH := handlers.NewDonorHandler(bH, mysql)
	requestsH := handlers.NewRequestHandler(bH, mysql)

	goji.Get("/login/", http.RedirectHandler("/login", 301))
	goji.Get("/login", bH.Route(adminH.ShowLogin))
	goji.Post("/login", bH.Route(adminH.DoLogin))
	goji.NotFound(bH.NotFound)

	admin := web.New()
	goji.Handle("/*", admin)
	admin.NotFound(bH.NotFound)
	admin.Use(middleware.NewAuth(cookieHandler))

	admin.Get("/", bH.Route(dashH.ShowDashboard))
	admin.Get("/administrators", bH.Route(adminH.ShowAdmins))
	admin.Get("/bloodbanks", bH.Route(bloodbankH.FetchBloodBanks))
	admin.Get("/donors", bH.Route(donorsH.FetchDonors))
	admin.Get("/requests", bH.Route(requestsH.FetchRequests))
	admin.Get("/logout", bH.Route(adminH.DoLogout))

	goji.Serve()
}
Beispiel #10
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 #11
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 #12
0
func err() {
	// custom 404
	g.NotFound(notFound)
}
Beispiel #13
0
func (ctr *Controller) RouteNotFound(rt *Route) {
	goji.NotFound(handlerWrap(rt))
}