// standardHttp starts serving standard HTTP (api/web) requests, to be used by normal clients func standardHttp(discovery bool) { m := martini.Classic() switch strings.ToLower(config.Config.AuthenticationMethod) { case "basic": { if config.Config.HTTPAuthUser == "" { // Still allowed; may be disallowed in future versions log.Warning("AuthenticationMethod is configured as 'basic' but HTTPAuthUser undefined. Running without authentication.") } m.Use(auth.Basic(config.Config.HTTPAuthUser, config.Config.HTTPAuthPassword)) } case "multi": { if config.Config.HTTPAuthUser == "" { // Still allowed; may be disallowed in future versions log.Fatal("AuthenticationMethod is configured as 'multi' but HTTPAuthUser undefined") } m.Use(auth.BasicFunc(func(username, password string) bool { if username == "readonly" { // Will be treated as "read-only" return true } return auth.SecureCompare(username, config.Config.HTTPAuthUser) && auth.SecureCompare(password, config.Config.HTTPAuthPassword) })) } default: { // We inject a dummy User object because we have function signatures with User argument in api.go m.Map(auth.User("")) } } m.Use(gzip.All()) // Render html templates from templates directory m.Use(render.Renderer(render.Options{ Directory: "resources", Layout: "templates/layout", HTMLContentType: "text/html", })) m.Use(martini.Static("resources/public")) inst.SetMaintenanceOwner(logic.ThisHostname) log.Info("Starting HTTP") if discovery { go logic.ContinuousDiscovery() } inst.ReadClusterAliases() http.API.RegisterRequests(m) http.Web.RegisterRequests(m) // Serve if err := nethttp.ListenAndServe(config.Config.ListenAddress, m); err != nil { log.Fatale(err) } }
func main() { m := martini.Classic() m.Use(gzip.All()) // render html templates from templates directory m.Use(render.Renderer(render.Options{ Layout: "layout", })) m.Use(DB()) m.Get("/", func(r render.Render, db *mgo.Database) { data := map[string]interface{}{"quotes": GetAll(db)} r.HTML(200, "list", data) }) m.Post("/", binding.Form(Quote{}), func(r render.Render, db *mgo.Database, quote Quote) { db.C("quotes").Insert(quote) data := map[string]interface{}{"quotes": GetAll(db)} r.HTML(200, "list", data) }) m.Run() }
func main() { log.Info("启动") //读取配置文件 base.BaseConfig.Read("config.json") // 初始化数据库 base.InitDb() // 检查文件完整性 //err := base.CheckFiles() //if(err!=nil){ // log.Error(err) // return //} m := martini.Classic() // gzip支持 m.Use(gzip.All()) // 模板支持 m.Use(render.Renderer()) // m.Get("/meta.js", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/javascript") w.Write([]byte(base.GetMetaJs())) }) // websocket 支持 m.Get("/ws", websocket.Handler(base.WsHandler).ServeHTTP) m.NotFound(func(r render.Render) { r.HTML(404, "404", nil) }) log.Info(fmt.Sprintf("访问地址 http://localhost:%d", base.BaseConfig.Web.Port)) // 端口号 http.ListenAndServe(fmt.Sprintf(":%d", base.BaseConfig.Web.Port), m) // m.Run() log.Info("退出") }
func App() *martini.ClassicMartini { m := martini.Classic() m.Use(gzip.All()) m.Use(render.Renderer(render.Options{ Directory: "templates", })) m.Use(cors.Allow(&cors.Options{ AllowAllOrigins: true, })) m.Get("", Index) m.Group("/repos", func(r martini.Router) { r.Get("", ReposIndex) r.Get("/:name", ReposShow) }) m.Group("/orgs", func(r martini.Router) { r.Get("", OrgsIndex) r.Get("/:id", OrgsShow) }) m.Group("/users", func(r martini.Router) { r.Get("", UserIndex) r.Get("/:id", UserShow) }) m.Get("/stats", StatsIndex) m.Get("/issues", IssuesIndex) return m }
// Http starts serving HTTP (api/web) requests func Http() { martini.Env = martini.Prod m := martini.Classic() if config.Config.HTTPAuthUser != "" { m.Use(auth.Basic(config.Config.HTTPAuthUser, config.Config.HTTPAuthPassword)) } m.Use(gzip.All()) // Render html templates from templates directory m.Use(render.Renderer(render.Options{ Directory: "resources", Layout: "templates/layout", HTMLContentType: "text/html", })) m.Use(martini.Static("resources/public")) go agent.ContinuousOperation() log.Infof("Starting HTTP on port %d", config.Config.HTTPPort) http.API.RegisterRequests(m) // Serve if config.Config.UseSSL { log.Info("Serving via SSL") err := nethttp.ListenAndServeTLS(fmt.Sprintf(":%d", config.Config.HTTPPort), config.Config.SSLCertFile, config.Config.SSLPrivateKeyFile, m) if err != nil { log.Fatale(err) } } else { nethttp.ListenAndServe(fmt.Sprintf(":%d", config.Config.HTTPPort), m) } }
func mount(war string) { m := martini.Classic() m.Handlers(martini.Recovery()) m.Use(gzip.All()) m.Use(martini.Static(war, martini.StaticOptions{SkipLogging: true})) // m.Use(render.Renderer(render.Options{ // Extensions: []string{".html", ".shtml"}, // })) // m.Use(render.Renderer()) // m.Use(midTextDefault) //map web m.Use(func(w http.ResponseWriter, c martini.Context) { web := &Web{w: w} c.Map(web) }) m.Group("/test", func(api martini.Router) { api.Get("", mainHandler) api.Get("/1", test1Handler) api.Get("/2", test2Handler) }) http.Handle("/", m) }
// NewWebService creates a new web service ready to run. func NewWebService() *martini.Martini { m := martini.New() m.Handlers(loggerMiddleware(), martini.Recovery(), gzip.All()) r := newRouter() m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) return m }
// Http starts serving HTTP (api/web) requests func Http() { martini.Env = martini.Prod m := martini.Classic() if config.Config.HTTPAuthUser != "" { m.Use(auth.Basic(config.Config.HTTPAuthUser, config.Config.HTTPAuthPassword)) } m.Use(gzip.All()) // Render html templates from templates directory m.Use(render.Renderer(render.Options{ Directory: "resources", Layout: "templates/layout", HTMLContentType: "text/html", })) m.Use(martini.Static("resources/public")) if config.Config.UseMutualTLS { m.Use(ssl.VerifyOUs(config.Config.SSLValidOUs)) } go agent.ContinuousOperation() log.Infof("Starting HTTP on port %d", config.Config.HTTPPort) http.API.RegisterRequests(m) listenAddress := fmt.Sprintf(":%d", config.Config.HTTPPort) // Serve if config.Config.UseSSL { if len(config.Config.SSLCertFile) == 0 { log.Fatale(errors.New("UseSSL is true but SSLCertFile is unspecified")) } if len(config.Config.SSLPrivateKeyFile) == 0 { log.Fatale(errors.New("UseSSL is true but SSLPrivateKeyFile is unspecified")) } log.Info("Starting HTTPS listener") tlsConfig, err := ssl.NewTLSConfig(config.Config.SSLCAFile, config.Config.UseMutualTLS) if err != nil { log.Fatale(err) } if err = ssl.AppendKeyPair(tlsConfig, config.Config.SSLCertFile, config.Config.SSLPrivateKeyFile); err != nil { log.Fatale(err) } if err = ssl.ListenAndServeTLS(listenAddress, m, tlsConfig); err != nil { log.Fatale(err) } } else { log.Info("Starting HTTP listener") if err := nethttp.ListenAndServe(listenAddress, m); err != nil { log.Fatale(err) } } log.Info("Web server started") }
func main() { fmt.Println("hello") go freeAlloc() m := martini.Classic() m.Handlers(gzip.All(), martini.Recovery()) Mount(m, 100) log.Printf("start gateway on %s\n", 5050) log.Fatal(http.ListenAndServe(":5050", nil)) // m.RunOnAddr(":5050") }
func init() { // BASE_URL, AUTH_USER and AUTH_PASS, AWS_S3_BASE_URL are not required or else wercker tests would fail baseURL = os.Getenv("BASE_URL") authUser = os.Getenv("AUTH_USER") authPass = os.Getenv("AUTH_PASS") s3BaseURL = os.Getenv("AWS_S3_BASE_URL") if awsAuth, err := aws.EnvAuth(); err != nil { // not required or else wercker tests would fail log.Println(err) } else { // TODO(jrubin) allow region to be chosen by env variable s3Data := s3.New(awsAuth, aws.USWest2) s3Bucket = s3Data.Bucket(os.Getenv("AWS_S3_BUCKET_NAME")) } m = martini.Classic() m.Use(gzip.All()) m.Use(render.Renderer()) m.Get("/", func() string { return "hello, world" }) m.Post( "/v1/transcribe", auth.Basic(authUser, authPass), strict.Accept("application/json"), strict.ContentType("application/x-www-form-urlencoded"), binding.Bind(transcribeData{}), binding.ErrorHandler, handleTranscribe, ) m.Post( "/v1/transcribe/process", strict.ContentType("application/x-www-form-urlencoded"), binding.Bind(telapi.TranscribeCallbackData{}), binding.ErrorHandler, handleTranscribeProcess, ) m.Post( "/v1/transcribe/upload", auth.Basic(authUser, authPass), strict.Accept("application/json"), binding.MultipartForm(transcribeUploadData{}), binding.ErrorHandler, handleTranscribeUpload, ) m.Router.NotFound(strict.MethodNotAllowed, strict.NotFound) }
func NewApiServer() http.Handler { m := martini.New() m.Use(martini.Recovery()) m.Use(render.Renderer()) m.Use(func(w http.ResponseWriter, req *http.Request, c martini.Context) { path := req.URL.Path if req.Method == "GET" && strings.HasPrefix(path, "/") { var remoteAddr = req.RemoteAddr var headerAddr string for _, key := range []string{"X-Real-IP", "X-Forwarded-For"} { if val := req.Header.Get(key); val != "" { headerAddr = val break } } fmt.Printf("API call %s from %s [%s]\n", path, remoteAddr, headerAddr) //if ip := strings.Split(remoteAddr,":");ip[0] != "172.17.140.52" { // w.WriteHeader(404) // return //} } c.Next() }) api := &apiServer{Version: "1.00", Compile: "go"} api.Load() api.StartDaemonRoutines() m.Use(gzip.All()) m.Use(func(req *http.Request, c martini.Context, w http.ResponseWriter) { if req.Method == "GET" && strings.HasPrefix(req.URL.Path, "/teampickwrwithoutjson") { w.Header().Set("Content-Type", "text/html; charset=utf-8") } else { w.Header().Set("Access-Control-Allow-Origin", "*") //允许访问所有域 w.Header().Add("Access-Control-Allow-Headers", "Content-Type") //header的类型 w.Header().Set("Content-Type", "application/json; charset=utf-8") } }) r := martini.NewRouter() r.Get("/", func(r render.Render) { r.Redirect("/overview") }) r.Get("/overview", api.showOverview) r.Get("/fetch/:account_id", api.fetchId) r.Get("/fetchupdate", api.fetchUpdate) r.Get("/teampick/:herolist", api.teamPick) r.Get("/teampickwr/:herolist", api.teamPickWinRate) r.Get("/teampickwrwithoutjson/:herolist", api.teamPickWinRateWithoutJSON) m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) return m }
func main() { var config, port, api string flag.StringVar(&config, "c", "config.json", "Config file") flag.StringVar(&port, "p", "8080", "Port") flag.StringVar(&api, "a", "DEFAULT", "API key") flag.Usage = func() { fmt.Fprintf(os.Stderr, `Usage: %s [options] Barycenter serves a JSON configuration file over HTTP using basic authentication (so run it over SSL). Run an endpoint as follows: %s -c config.json -a DEFAULT -p 8080 You can then make a request against the endpoint. curl -u DEFAULT: 127.0.0.1:8080 OPTIONS: `, os.Args[0], os.Args[0]) flag.PrintDefaults() } flag.Parse() if flag.NArg() != 0 { flag.Usage() os.Exit(1) } json, err := ioutil.ReadFile(config) if err != nil { log.Fatalf("Could not read configuration: %s", err) } m := martini.Classic() m.Use(gzip.All()) m.Use(auth.Basic(api, "")) m.Get("/", func(w http.ResponseWriter, req *http.Request) string { w.Header().Set("Content-Type", "application/json; charset=utf-8") return string(json) }) http.ListenAndServe(":"+port, m) }
func main() { m := martini.Classic() //Make sure to include the Gzip middleware above other middleware that alter the response body (like the render middleware). m.Use(gzip.All()) // render html templates from templates directory m.Use(render.Renderer(render.Options{ Layout: "layout", })) controllers.RouterInit(m) m.Run() }
func main() { var serverPort int var localhost bool flag.StringVar(&ledgerFileName, "f", "", "Ledger file name (*Required).") flag.StringVar(&reportConfigFileName, "r", "", "Report config file name (*Required).") flag.IntVar(&serverPort, "port", 8056, "Port to listen on.") flag.BoolVar(&localhost, "localhost", false, "Listen on localhost only.") flag.Parse() if len(ledgerFileName) == 0 || len(reportConfigFileName) == 0 { flag.Usage() return } go func() { for { var rLoadData reportConfigStruct toml.DecodeFile(reportConfigFileName, &rLoadData) reportConfigData = rLoadData time.Sleep(time.Minute * 5) } }() m := martini.Classic() m.Use(gzip.All()) m.Use(staticbin.Static("public", Asset)) m.Get("/ledger", ledgerHandler) m.Get("/accounts", accountsHandler) m.Get("/account/:accountName", accountHandler) m.Get("/report/:reportName", reportHandler) m.Get("/", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/accounts", http.StatusFound) }) fmt.Println("Listening on port", serverPort) listenAddress := "" if localhost { listenAddress = fmt.Sprintf("127.0.0.1:%d", serverPort) } else { listenAddress = fmt.Sprintf(":%d", serverPort) } http.ListenAndServe(listenAddress, m) }
func main() { m := martini.Classic() //Make sure to include the Gzip middleware above other middleware that alter the response body (like the render middleware). m.Use(gzip.All()) // render html templates from templates directory m.Use(render.Renderer(render.Options{ Layout: "layout", })) store := sessions.NewCookieStore([]byte("secret123")) m.Use(sessions.Sessions("mysession", store)) controllers.RouterInit(m) models.ModelInit() m.Run() }
func setupMartini(db *sql.DB, conf *config.Config, mediaManager *media.Manager) { m := martini.Classic() m.Use(auth.SpecAuth(conf.Auth.Username, conf.Auth.Password, conf.Auth.ApiPath)) m.Use(gzip.All()) m.Map(db) m.Map(conf) m.Map(mediaManager) rendererOption := render.Options{ Layout: "layout", Funcs: []htmlTemplate.FuncMap{ { "echoActiveLink": blahTemplate.EchoActiveLink, "echoPageAction": blahTemplate.EchoPageAction, "echoSelectSelected": blahTemplate.EchoSelectSelected, "echoMediaUpload": blahTemplate.EchoMediaUpload, "echoMediaDisplay": blahTemplate.EchoMediaDisplay, "echoTimestamp": blahTemplate.EchoTimeStamp, "echoLanguage": blahTemplate.EchoLanguage, }, }, IndentJSON: true, } m.Use(render.Renderer(rendererOption)) entity.SetMediaBaseUrl(conf.Blah.BaseMediaUri) blahTemplate.Module(m) controller.Module(m, conf.Auth.ApiPath) m.Get("/", ShowWelcome) m.Run() }
// agentsHttp startes serving agents API requests func agentsHttp() { m := martini.Classic() m.Use(gzip.All()) m.Use(render.Renderer()) log.Info("Starting agents HTTP") go logic.ContinuousAgentsPoll() http.AgentsAPI.RegisterRequests(m) // Serve if config.Config.AgentsUseSSL { log.Info("Serving via SSL") err := nethttp.ListenAndServeTLS(":3001", config.Config.SSLCertFile, config.Config.SSLPrivateKeyFile, m) if err != nil { log.Fatale(err) } } else { nethttp.ListenAndServe(":3001", m) } }
// agentsHttp startes serving agents HTTP or HTTPS API requests func agentsHttp() { m := martini.Classic() m.Use(gzip.All()) m.Use(render.Renderer()) if config.Config.AgentsUseMutualTLS { m.Use(ssl.VerifyOUs(config.Config.AgentSSLValidOUs)) } log.Info("Starting agents listener") agent.InitHttpClient() go logic.ContinuousAgentsPoll() http.AgentsAPI.URLPrefix = config.Config.URLPrefix http.AgentsAPI.RegisterRequests(m) // Serve if config.Config.AgentsUseSSL { log.Info("Starting agent HTTPS listener") tlsConfig, err := ssl.NewTLSConfig(config.Config.AgentSSLCAFile, config.Config.AgentsUseMutualTLS) if err != nil { log.Fatale(err) } tlsConfig.InsecureSkipVerify = config.Config.AgentSSLSkipVerify if err = ssl.AppendKeyPairWithPassword(tlsConfig, config.Config.AgentSSLCertFile, config.Config.AgentSSLPrivateKeyFile, agentSSLPEMPassword); err != nil { log.Fatale(err) } if err = ssl.ListenAndServeTLS(config.Config.AgentsServerPort, m, tlsConfig); err != nil { log.Fatale(err) } } else { log.Info("Starting agent HTTP listener") if err := nethttp.ListenAndServe(config.Config.AgentsServerPort, m); err != nil { log.Fatale(err) } } log.Info("Agent server started") }
func NewApi() *martini.Martini { m := martini.New() // Setup middleware m.Use(martini.Recovery()) m.Use(martini.Logger()) m.Use(gzip.All()) m.Use(func(w http.ResponseWriter, req *http.Request) { if req.URL.Path != "/mtg/cards/random" { w.Header().Set("Cache-Control", "public,max-age=3600") } w.Header().Set("Content-Type", "application/json; charset=utf-8") w.Header().Set("Access-Control-Allow-Origin", "*") w.Header().Set("License", "The textual information presented through this API about Magic: The Gathering is copyrighted by Wizards of the Coast.") w.Header().Set("Disclaimer", "This API is not produced, endorsed, supported, or affiliated with Wizards of the Coast.") w.Header().Set("Pricing", "store.tcgplayer.com allows you to buy cards from any of our vendors, all at the same time, in a simple checkout experience. Shop, Compare & Save with TCGplayer.com!") w.Header().Set("Strict-Transport-Security", "max-age=86400") }) r := martini.NewRouter() r.Get("/ping", Ping) r.Get("/mtg/cards", HandleCards) r.Get("/mtg/cards/typeahead", HandleTypeahead) r.Get("/mtg/cards/random", HandleRandomCard) r.Get("/mtg/cards/:id", HandleCard) r.Get("/mtg/sets", HandleSets) r.Get("/mtg/sets/:id", HandleSet) r.Get("/mtg/colors", HandleTerm("colors")) r.Get("/mtg/supertypes", HandleTerm("supertypes")) r.Get("/mtg/subtypes", HandleTerm("subtypes")) r.Get("/mtg/types", HandleTerm("types")) r.NotFound(NotFound) m.Action(r.Handle) return m }
func main() { store.Setup() m := martini.New() router := martini.NewRouter() router.NotFound(func() (int, []byte) { return 404, []byte("Requested page not found.") }) m.Use(martini.Logger()) m.Use(martini.Recovery()) m.Use(gzip.All()) m.Use(func(c martini.Context, w http.ResponseWriter) { w.Header().Set("Content-Type", "application/json; charset=utf-8") }) router.Group("/chats", func(r martini.Router) { r.Get("/userchats/:userid", chat.GetChats) // Get list of all chats for a user r.Get("/messages/:chatid", chat.ViewMessages) // View chat messages for a chat r.Post("/newchat", chat.NewChat) // Create a new chat with specific users r.Post("/sendmessage/:chatid", chat.SendMessage) // Send message to a chat as a user }) router.Group("/users", func(r martini.Router) { r.Get("/get", users.GetUsers) // Get list of all users r.Get("/new/:userName", users.NewUser) // Make a new user r.Post("/delete/:userid", users.DeleteUser) // Delete a user with a specific id }) m.MapTo(router, (*martini.Routes)(nil)) m.Action(router.Handle) m.Run() }
// standardHttp starts serving HTTP or HTTPS (api/web) requests, to be used by normal clients func standardHttp(discovery bool) { m := martini.Classic() switch strings.ToLower(config.Config.AuthenticationMethod) { case "basic": { if config.Config.HTTPAuthUser == "" { // Still allowed; may be disallowed in future versions log.Warning("AuthenticationMethod is configured as 'basic' but HTTPAuthUser undefined. Running without authentication.") } m.Use(auth.Basic(config.Config.HTTPAuthUser, config.Config.HTTPAuthPassword)) } case "multi": { if config.Config.HTTPAuthUser == "" { // Still allowed; may be disallowed in future versions log.Fatal("AuthenticationMethod is configured as 'multi' but HTTPAuthUser undefined") } m.Use(auth.BasicFunc(func(username, password string) bool { if username == "readonly" { // Will be treated as "read-only" return true } return auth.SecureCompare(username, config.Config.HTTPAuthUser) && auth.SecureCompare(password, config.Config.HTTPAuthPassword) })) } default: { // We inject a dummy User object because we have function signatures with User argument in api.go m.Map(auth.User("")) } } m.Use(gzip.All()) // Render html templates from templates directory m.Use(render.Renderer(render.Options{ Directory: "resources", Layout: "templates/layout", HTMLContentType: "text/html", })) m.Use(martini.Static("resources/public")) if config.Config.UseMutualTLS { m.Use(ssl.VerifyOUs(config.Config.SSLValidOUs)) } inst.SetMaintenanceOwner(process.ThisHostname) if discovery { log.Info("Starting Discovery") go logic.ContinuousDiscovery() } log.Info("Registering endpoints") http.API.RegisterRequests(m) http.Web.RegisterRequests(m) // Serve if config.Config.ListenSocket != "" { log.Infof("Starting HTTP listener on unix socket %v", config.Config.ListenSocket) unixListener, err := net.Listen("unix", config.Config.ListenSocket) if err != nil { log.Fatale(err) } defer unixListener.Close() if err := nethttp.Serve(unixListener, m); err != nil { log.Fatale(err) } } else if config.Config.UseSSL { log.Info("Starting HTTPS listener") tlsConfig, err := ssl.NewTLSConfig(config.Config.SSLCAFile, config.Config.UseMutualTLS) if err != nil { log.Fatale(err) } tlsConfig.InsecureSkipVerify = config.Config.SSLSkipVerify if err = ssl.AppendKeyPairWithPassword(tlsConfig, config.Config.SSLCertFile, config.Config.SSLPrivateKeyFile, sslPEMPassword); err != nil { log.Fatale(err) } if err = ssl.ListenAndServeTLS(config.Config.ListenAddress, m, tlsConfig); err != nil { log.Fatale(err) } } else { log.Infof("Starting HTTP listener on %+v", config.Config.ListenAddress) if err := nethttp.ListenAndServe(config.Config.ListenAddress, m); err != nil { log.Fatale(err) } } log.Info("Web server started") }
func main() { m := martini.Classic() // Gzip all m.Use(gzip.All()) // Create sessions cookie store store := sessions.NewCookieStore([]byte(utils.AppCfg.SecretKey())) m.Use(sessions.Sessions("pixelrelay", store)) // Setup render options m.Use(render.Renderer(render.Options{ Directory: "templates", // Specify what path to load the templates from. Layout: "layout", // Specify a layout template. Layouts can call {{ yield }} to render the current template. Charset: "UTF-8", // Sets encoding for json and html content-types. Delims: render.Delims{Left: "{[", Right: "]}"}, // Sets delimiters to the specified strings. })) // Setup DB dbh := db.Init(&db.Dbh{}) m.Map(dbh) // Setup static file handling opts := martini.StaticOptions{SkipLogging: false, Expires: utils.ExpiresHeader} m.Use(martini.Static("static", opts)) // Auth user and assign to session m.Use(middleware.UserAuth(models.User{}, dbh)) // Encoder for .html or .json encoding m.Use(encoder.MapEncoder) // Setup Page p := models.InitPage(&models.Page{}) m.Map(p) // Set up routes m.Get("/", controllers.Index) // Images m.Get("/image/:name", middleware.VerifyFile, controllers.ImagePage) m.Get("/o/:name", middleware.VerifyFile, controllers.Image) m.Get("/i/:name", middleware.VerifyFile, controllers.ImageModified) m.Get("/t/:name", middleware.VerifyFile, controllers.Thumb) m.Get("/image/trash/:album/:name", middleware.AuthRequired, controllers.ImageTrash) m.Get("/image/recover/:album/:name", middleware.AuthRequired, controllers.ImageRecover) // Albums m.Get("/albums", controllers.Albums) m.Get("/album/:name", controllers.Album) m.Get("/album/:name/qr", controllers.QR) m.Get("/:user/albums", controllers.Albums) m.Get("/:user/album/:name", controllers.Album) m.Get("/album/:name/private/:state", controllers.AlbumPrivate) m.Get("/album/:name/:key", controllers.Album) m.Post("/album/create", middleware.AuthRequired, controllers.AlbumCreate) m.Post("/album/update", middleware.AuthRequired, controllers.AlbumUpdate) m.Post("/album/delete/:name", middleware.AuthRequired, controllers.AlbumDelete) m.Post("/album/recover/:name", middleware.AuthRequired, controllers.AlbumRecover) m.Post("/album/move", middleware.AuthRequired, controllers.AlbumMove) // Tag m.Get("/tags", controllers.Tags) m.Get("/tag/:tag", controllers.Tagged) m.Post("/tag", middleware.AuthRequired, controllers.TagImage) // Auth m.Get("/login", controllers.Login) m.Post("/login", binding.Bind(forms.Login{}), binding.ErrorHandler, controllers.LoginPost) m.Get("/logout", controllers.Logout) // Upload m.Post("/up", middleware.Verify, binding.MultipartForm(models.ImageUpload{}), controllers.UploadImage) // 404 m.NotFound(controllers.NotFound) // Account m.Get("/account", middleware.AuthRequired, controllers.Account) // Profile m.Get("/profile/:name", controllers.Profile) // Testing m.Get("/test/hash", test.Hash) m.Get("/test/hash/:user_id/:image_id", test.Hash) m.Get("/test/list", middleware.AuthRequired, test.List) m.Get("/test/listdb", middleware.AuthRequired, test.ListDB) m.Get("/test/listt", middleware.AuthRequired, test.ListThumb) m.Get("/test/uploader", middleware.AuthRequired, test.Uploader) // Start server and begin listening for HTTP requests // Watch for non-https requests and redirect to https // If request method is POST and path is /up // discard file and redirect to correct https route log.Printf("Listening for \x1b[32;1mHTTP\x1b[0m connections on \x1b[32;1m%s\x1b[0m\n", utils.AppCfg.ListenOn()) go http.ListenAndServe(utils.AppCfg.ListenOn(), http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { urlPath := r.URL.Path url := strings.Join([]string{utils.AppCfg.Url(), urlPath}, "") // Check if path is for the Upload controller. // Redirect client to HTTPS end point if urlPath == "/up" && r.Method == "POST" { ur := models.UploadResult{ Code: http.StatusFound, Result: "HTTPS Required", Name: url, } log.Println(ur.String()) // Move uploaded file to DevNull file, _, _ := r.FormFile("uploaded_file") defer file.Close() out, err := os.Create(os.DevNull) if err != nil { log.Println(err) } defer out.Close() _, err = io.Copy(out, file) if err != nil { log.Println(err) } // Respond with JSON that server requires HTTPS and correct path. w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("Expires", utils.ExpiresHeader()) w.Header().Set("Content-Type", "application/json") fmt.Fprint(w, ur) return } log.Println("Redirect: ", url) http.Redirect(w, r, url, http.StatusFound) })) // Start server and begin listening for TLS requests log.Printf("Listening for \x1b[32;1mTLS\x1b[0m connections on \x1b[32;1m%s\x1b[0m\n", utils.AppCfg.TLSListenOn()) go http.ListenAndServeTLS(utils.AppCfg.TLSListenOn(), "./tls/cert.pem", "./tls/key.pem", m) /****************************************** * INITIAL SETUP * * Creates the initial tables * Populates the default admin user * * Potential security risks are present * if this mode is left running. * restart server with the "-init" flag * unset. * * usage: -init */ if *flagInit { fmt.Println("\x1b[31;1mInitial Setup flag (-init) has been set to \x1b[32;1mTRUE\x1b[0m") fmt.Println("\x1b[31;1mOnce setup is complete please restart server with this flag disabled.\x1b[0m") // Add default tables dbh.AddTables() su := martini.Classic() store := sessions.NewCookieStore([]byte(utils.AppCfg.SecretKey())) su.Use(sessions.Sessions("pixelrelay", store)) su.Use(render.Renderer(render.Options{ Directory: "templates", // Specify what path to load the templates from. Layout: "layout", // Specify a layout template. Layouts can call {{ yield }} to render the current template. Charset: "UTF-8", // Sets encoding for json and html content-types. })) su.Get("/setup", controllers.SetupAdmin) su.Post("/setup", binding.Bind(forms.SetupAdmin{}), binding.ErrorHandler, controllers.SetupAdminPost) // Start server and begin listening for requests log.Printf("Listening for connections on \x1b[32;1m%s\x1b[0m\n", utils.AppCfg.ListenOnSetup()) go http.ListenAndServe(utils.AppCfg.ListenOnSetup(), su) } /****************************************** * MIGRATE DATABASE UPDATES * * Migrates changes to database tables * * You should backup the database before * migrating. As there is a potential risk * of data loss * * usage: -migrate */ if *flagMigrate { dbh.MigrateDB() } select {} }
func main() { var serverPort int var localhost bool flag.IntVar(&serverPort, "port", 8056, "Port to listen on.") flag.BoolVar(&localhost, "localhost", false, "Listen on localhost only.") flag.Parse() var cardata []Record var carmutex sync.RWMutex m := martini.Classic() m.Use(gzip.All()) m.Use(staticbin.Static("public", Asset)) carfunc := func(res http.ResponseWriter, r *http.Request) { fmt.Println(time.Now()) decoder := json.NewDecoder(r.Body) var rec Record err := decoder.Decode(&rec) if err != nil { log.Println(err) } recTime := time.Unix(0, 0) recTime = recTime.Add(time.Millisecond * time.Duration(rec.Timestamp)) rec.DateTime = recTime fmt.Println(recTime) for rName, reading := range rec.Readings { if reading != "" && reading != "NO DATA" { segs := validValue.FindAllStringSubmatch(reading, -1) if len(segs) > 0 && len(segs[0]) > 2 { val := segs[0][1] //fmt.Println(rName, strings.TrimSpace(segs[0][1]), strings.TrimSpace(segs[0][2])) switch rName { case "BAROMETRIC_PRESSURE": rec.BarometricPressure = val case "INTAKE_MANIFOLD_PRESSURE": rec.IntakeManifoldPressure = val case "ENGINE_RPM": rec.EngineRPM = val case "ENGINE_COOLANT_TEMP": rec.EngineCoolantTemp = val case "AMBIENT_AIR_TEMP": rec.AmbientAirTemp = val case "SPEED": rec.Speed = val case "THROTTLE_POS": rec.ThrottlePos = val case "AIR_INTAKE_TEMP": rec.AirIntakeTemp = val } } } } fmt.Println(rec) carmutex.Lock() // Get latest time clear all trip data if the time we are // receiving is over an hour after the last time received. if len(cardata) > 0 { recentTime := cardata[len(cardata)-1].DateTime if rec.DateTime.Sub(recentTime) > time.Hour { cardata = []Record{} } } // Append received record to trip. cardata = append(cardata, rec) carmutex.Unlock() } m.Put("/", carfunc) m.Put("/data", carfunc) m.Put("/data/", carfunc) carview := func(w http.ResponseWriter, r *http.Request) { type DataSet struct { FieldName string RGBColor string Values []string } var chartData struct { RangeStart, RangeEnd time.Time Labels []string DataSets []DataSet } carmutex.RLock() chartData.DataSets = []DataSet{ {FieldName: "Speed (km/h)", RGBColor: "220,220,220", Values: make([]string, len(cardata))}, {FieldName: "Throttle (%)", RGBColor: "151,187,205", Values: make([]string, len(cardata))}, {FieldName: "RPM (x100)", RGBColor: "70, 191, 189", Values: make([]string, len(cardata))}, } for rIdx, rec := range cardata { if chartData.RangeStart.IsZero() { chartData.RangeStart = rec.DateTime } chartData.RangeEnd = rec.DateTime chartData.Labels = append(chartData.Labels, rec.DateTime.Format("15:04:05")) chartData.DataSets[0].Values[rIdx] = rec.Speed chartData.DataSets[1].Values[rIdx] = rec.ThrottlePos rpm, _ := strconv.ParseInt(rec.EngineRPM, 10, 64) chartData.DataSets[2].Values[rIdx] = fmt.Sprint(rpm / 100) } carmutex.RUnlock() t, err := parseAssets("templates/template.linechart.html", "templates/template.nav.html") if err != nil { http.Error(w, err.Error(), 500) return } err = t.Execute(w, chartData) if err != nil { http.Error(w, err.Error(), 500) } } m.Get("/", func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/carview", http.StatusFound) }) m.Get("/carview", carview) fmt.Println("Listening on port", serverPort) listenAddress := "" if localhost { listenAddress = fmt.Sprintf("127.0.0.1:%d", serverPort) } else { listenAddress = fmt.Sprintf(":%d", serverPort) } http.ListenAndServe(listenAddress, m) }
func main() { kingpin.UsageTemplate(kingpin.CompactUsageTemplate).Version("1.0").Author("Christoph Mewes") kingpin.CommandLine.Help = "HTTP application server to run the Raziel secret management" kingpin.Parse() if *configFile == "" { kingpin.FatalUsage("No configuration file (--config) given!") } // load config file err := loadConfigFile() if err != nil { kingpin.FatalUsage(err.Error()) } // connect to database database, err := sqlx.Connect("mysql", config.Database.Source) if err != nil { kingpin.FatalUsage(err.Error()) } validateMasterPassword(database) // init restriction handlers restrictionHandlers = make(map[string]RestrictionHandler) addRestrictionHandler(ApiKeyRestriction{}) addRestrictionHandler(TlsCertRestriction{}) addRestrictionHandler(OriginIpRestriction{}) addRestrictionHandler(DateRestriction{}) addRestrictionHandler(TimeRestriction{}) addRestrictionHandler(FileRestriction{}) addRestrictionHandler(HitLimitRestriction{}) addRestrictionHandler(ThrottleRestriction{}) // init templates templateManager = NewTemplateManager("templates") // setup basic Martini server martini.Env = martini.Dev if config.Environment == "production" || config.Environment == "prod" { martini.Env = martini.Prod } m := martini.New() m.Use(martini.Logger()) m.Use(gzip.All()) m.Use(martini.Recovery()) m.Use(martini.Static("www")) m.Use(method.Override()) // force all handlers to run inside a transaction m.Use(func(c martini.Context) { tx := database.MustBegin() defer func() { if r := recover(); r != nil { tx.Rollback() panic(r) } }() c.Map(tx) c.Next() err := tx.Commit() if err != nil { panic(err) } }) // setup session and CSRF support duration, err := time.ParseDuration(config.Session.Lifetime) if err != nil { log.Fatal("Invalid session lifetime configured: " + err.Error()) } sessions = NewSessionMiddleware(cookieOptions{ Name: config.Session.CookieName, MaxAge: duration, HttpOnly: true, Secure: config.Session.Secure, }) sessions.Setup(m) // re-compile all templates on each hit if martini.Env != martini.Prod { m.Use(func() { templateManager.Init() }) } // use a custom return handler to make our mini response structs possible // (this overwrites the existing handler) m.Map(newReturnHandler()) r := martini.NewRouter() m.MapTo(r, (*martini.Routes)(nil)) m.Action(r.Handle) martini := &martini.ClassicMartini{m, r} setupDashboardCtrl(martini) setupProfileCtrl(martini) setupLoginCtrl(martini) setupSecretsCtrl(martini) setupUsersCtrl(martini) setupConsumersCtrl(martini) setupAuditLogCtrl(martini) setupAccessLogCtrl(martini) setupDeliveryCtrl(martini) // setup our own http server and configure TLS srv := &http.Server{ Addr: config.Server.Listen, Handler: martini, TLSConfig: &tls.Config{ CipherSuites: config.CipherSuites(), }, } log.Fatal(srv.ListenAndServeTLS(config.Server.Certificate, config.Server.PrivateKey)) }
func init() { envFileName := martini.Env + ".env" err := godotenv.Load(envFileName) if err != nil { log.Fatalf("Error loading: %s", envFileName) } db = models.Connect() utils.GenKeyPairIfNone(os.Getenv("PRIVATE_KEY"), os.Getenv("PUBLIC_KEY")) PrivateKey = utils.GetKey(os.Getenv("PRIVATE_KEY")) PublicKey = utils.GetKey(os.Getenv("PUBLIC_KEY")) claims := map[string]interface{}{ "user_id": 1, "role": "admin", "exp": time.Now().UTC().Add(time.Hour * 6).Unix(), "iat": time.Now().UTC().Unix(), } auth, _ := utils.GenerateAuthToken(claims, PrivateKey) fmt.Println(auth) m = martini.New() // Setup middleware if os.Getenv("DEV_RUNNER") == "1" { m.Use(runnerMiddleware) } m.Use(analytics.Google(os.Getenv("GA"))) m.Use(gzip.All()) m.Use(martini.Recovery()) m.Use(martini.Logger()) m.Use(render.Renderer()) m.Use(martini.Static("public")) m.Map(db) // Setup routes gr := martini.NewRouter() gr.Group("/api", func(r martini.Router) { r.Get(`/latest`, routes.LatestIndex) r.Get(`/popular`, routes.PopularIndex) r.Get(`/media`, routes.MediaIndex) r.Get(`/media/head/:id`, routes.MediaHead) r.Get(`/media/play/:id`, routes.MediaPlay) r.Post(`/media`, utils.LoginRequired(PublicKey), binding.Bind(models.Media{}), routes.MediaCreate) r.Get("/media/new", utils.LoginRequired(PublicKey), routes.MediaNew) r.Get(`/media/:slug`, routes.MediaGet) r.Put(`/media/:id`, utils.LoginRequired(PublicKey), binding.Bind(models.Media{}), routes.MediaUpdate) r.Delete(`/media/:id`, utils.LoginRequired(PublicKey), routes.MediaDelete) r.Get(`/groups`, routes.GroupsIndex) r.Post(`/groups`, utils.LoginRequired(PublicKey), binding.Bind(models.Group{}), routes.GroupCreate) r.Get("/groups/new", utils.LoginRequired(PublicKey), routes.GroupNew) r.Get(`/group/:slug`, routes.GroupGet) r.Get(`/group/:slug/media`, routes.MediaForGroupGet) r.Put(`/group/:id`, utils.LoginRequired(PublicKey), binding.Bind(models.Group{}), routes.GroupUpdate) r.Delete(`/group/:id`, utils.LoginRequired(PublicKey), routes.GroupDelete) }) gr.Get(`/feed/:slug`, routes.FeedForGroupGet) gr.Get(`/stats`, utils.LoginRequired(PublicKey), workers.Stats) // Inject database // Add the router action m.Action(gr.Handle) }
func init() { flag.Parse() m := martini.Classic() m.Use(gzip.All()) m.Use(martini.Static("public")) store := sessions.NewCookieStore([]byte("dynamic-fab")) m.Use(sessions.Sessions("my_session", store)) m.Use(render.Renderer(render.Options{ Directory: "views", Layout: "layout", Extensions: []string{".tmpl", ".html"}, Funcs: []template.FuncMap{ { "StringsEqual": func(a, b string) bool { if strings.EqualFold(a, b) { return true } return false }, "ShortenString": func(s string, l int) string { if len(s) <= l { return s } return fmt.Sprintf("%s...", s[:l]) }, "IntegerGreater": func(x interface{}, y interface{}) bool { if x == nil || y == nil { return false } var xint int = 0 var yint int = 0 xtyp := reflect.TypeOf(x) switch xtyp.Kind() { case reflect.Int: xint = int(x.(int)) case reflect.Int32: xint = int(x.(int32)) case reflect.Int16: xint = int(x.(int16)) case reflect.Int64: xint = int(x.(int64)) } ytyp := reflect.TypeOf(y) switch ytyp.Kind() { case reflect.Int: yint = int(y.(int)) case reflect.Int32: yint = int(y.(int32)) case reflect.Int16: yint = int(y.(int16)) case reflect.Int64: yint = int(y.(int64)) } if xint <= yint { return false } return true }, }, }, Delims: render.Delims{"{{", "}}"}, Charset: "UTF-8", IndentJSON: true, HTMLContentType: "text/html", })) // Backend tasks m.Group("/admin", func(r martini.Router) { r.Get("", backend.Home) r.Get("/auth", auth.Index) r.Post("/auth", auth.Login) r.Get("/auth/out", auth.Logout) }) m.Group("/admin/banners", func(r martini.Router) { r.Get("", auth.Check, bannerAdmin.Index) r.Get("/:id", auth.Check, bannerAdmin.Edit) r.Post("/:id", auth.Check, bannerAdmin.Save) r.Delete("/:id", auth.Check, bannerAdmin.Delete) }) m.Group("/admin/content", func(r martini.Router) { r.Get("", auth.Check, contentAdmin.Index) r.Get("/:id", auth.Check, contentAdmin.Edit) r.Post("/:id", auth.Check, contentAdmin.Save) r.Delete("/:id", auth.Check, contentAdmin.Delete) }) m.Group("/admin/testimonials", func(r martini.Router) { r.Get("", auth.Check, testimonialAdmin.Index) r.Get("/:id", auth.Check, testimonialAdmin.Edit) r.Post("/:id", auth.Check, testimonialAdmin.Save) r.Delete("/:id", auth.Check, testimonialAdmin.Delete) }) m.Group("/admin/equipment", func(r martini.Router) { r.Get("", auth.Check, equipmentAdmin.Index) r.Get("/:id", auth.Check, equipmentAdmin.Edit) r.Post("/:id", auth.Check, equipmentAdmin.Save) r.Delete("/:id", auth.Check, equipmentAdmin.Delete) }) m.Group("/admin/quotes", func(r martini.Router) { r.Get("", auth.Check, quoteAdmin.Index) r.Post("/heading", auth.Check, quoteAdmin.SetHeading) r.Get("/:id", auth.Check, quoteAdmin.View) r.Delete("/:id", auth.Check, quoteAdmin.Delete) }) m.Group("/admin/about", func(r martini.Router) { r.Get("", auth.Check, aboutAdmin.Edit) r.Post("", auth.Check, aboutAdmin.Save) }) m.Get("/blob/:id", banners.Serve) m.Group("/api/banners", func(r martini.Router) { r.Get("", banners.All) r.Get("/:id", banners.Get) }) m.Group("/api/content", func(r martini.Router) { r.Get("", content.All) r.Get("/:id", content.Get) }) m.Group("/api/testimonials", func(r martini.Router) { r.Get("", testimonial.All) r.Get("/:id", testimonial.Get) }) m.Group("/api/equipment", func(r martini.Router) { r.Get("", equipment.All) r.Get("/:id", equipment.Get) }) m.Group("/api/quote", func(r martini.Router) { r.Post("", quote.Submit) r.Get("/heading", quote.Heading) }) m.Get("/api/aboutus", aboutus.Get) // m.Get("/adduser", auth.AddUser) // Serve Frontend m.Get("/**", func(rw http.ResponseWriter, req *http.Request, r render.Render) { bag := make(map[string]interface{}, 0) bag["Host"] = req.URL.Host r.HTML(200, "index", bag) }) http.Handle("/", m) }
func gzip_handler() martini.Handler { return gzip.All() }