func main() { m := martini.Classic() m.Post("/text", binding.Bind(DisplayMessage{}), createText) m.Post("/image", binding.MultipartForm(ImageMessage{}), createImage) m.Post("/display", binding.Bind(IDMessage{}), displayImage) m.Run() }
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) }
//martini Handler func UploadHandlers() []martini.Handler { var upload = func(fileData FileData, data UploadData, w http.ResponseWriter) { retJsonp := &UploadRetJsonp{MessengerJs: MessengerJs, UpTime: data.UpTime} if strings.ToUpper(data.Dir) != "IMAGE" { retJsonp.Err(w, "dir wrong:"+data.Dir) return } imgFile, err := fileData.ImgFile.Open() if err != nil { retJsonp.Err(w, "ImgFile:"+err.Error()) return } //取得bucket bucket, err := bucketdb.FindByName(data.Bucket) if err != nil { retJsonp.Err(w, "FindByName:"+err.Error()) return } if bucket.Uptoken == "" { if err := bucket.NewUptoken(); err != nil { retJsonp.Err(w, "NewUptoken:"+err.Error()) return } if err := bucket.Save(); err != nil { retJsonp.Err(w, "Save:"+err.Error()) return } } //上传内容到Qiniu var ret qio.PutRet // ret 变量用于存取返回的信息,详情见 qio.PutRet // uptoken 为业务服务器端生成的上传口令 // key:imgName 为文件存储的标识 // r:imgFile 为io.Reader类型,用于从其读取数据 // extra 为上传文件的额外信息,可为空, 详情见 qio.PutExtra, 可选 err = qio.Put(nil, &ret, bucket.Uptoken, fileData.ImgName(), imgFile, nil) if err != nil { bucket.LogErr() retJsonp.Err(w, "Put:"+err.Error()) return } //上传成功,返回给KindEditor //w.Header().Set("Content-type", "application/json") retJsonp.Respose(w, bucket.ImgUrl(ret.Key)) } return []martini.Handler{binding.MultipartForm(FileData{}), binding.Form(UploadData{}), upload} }
func main() { server := martini.Classic() config := InitConfig() //添加中间件 server.Use(render.Renderer(render.Options{ //render中间件可以把对象方便的序列化为xml或者json Directory: "./html", Extensions: []string{".html"}, Charset: "UTF-8", })) server.Use(martini.Static("public")) //静态文件服务 //添加路由 //第一个参数是url路径, //之后的参数是处理该路径请求的处理函数, //可以添加多个,依次调用 //方法名表示该路径的HTTP方法,表示只能用GET访问该路径。 server.Get("/", cookie.Bind(UserCookie{}), handleHome) //Group是父路径下添加子路径,下面url分别表示/sched/all, /sched/all, /sched/delete。 //在父路径里添加的处理函数在子路径中都会运行, //比如下面的cookie.Bind(UserCookie{}),该方法返回值是一个函数,表示这个路径以及所有的子路径都绑定了一个cookie。 server.Group("/sched", func(r martini.Router) { r.Post("/add", binding.Form(Sched{}), handleAddSched) r.Get("/all", handleGetSched) r.Post("/delete", handleDelSched) }, cookie.Bind(UserCookie{})) server.Group("/user", func(r martini.Router) { r.Post("/login", binding.Form(UserLoginForm{}), LoginHandler) r.Post("/logout") r.Post("/register", binding.Form(UserRegisterForm{}), RegisterHandler) r.Post("/checklogin", cookie.Bind(UserCookie{}), CheckLoginHandler) r.Group("/bkimg", func(rr martini.Router) { rr.Post("/upload", binding.MultipartForm(Bkimg{}), UploadBkimg) rr.Get("/get", GetBkimg) }, cookie.Bind(UserCookie{})) }) //映射服务 logger := log.New(os.Stdout, "[martini] ", log.Llevel|log.Lshortfile|log.Lmodule) //Map方法传入的对象可以被传入到处理函数的对应参数中。 server.Map(logger) server.Map(config) server.RunOnAddr(":" + config.Server.Port) }
func main() { m := martini.Classic() m.Use(render.Renderer(render.Options{ Directory: "templates", Extensions: []string{".html"}, })) m.Use(martini.Static("public")) m.Get("/", upload) m.Post("/mosaic", binding.MultipartForm(UploadForm{}), mosaic) TILESDB = make(map[string][3]float64) go tilesDB() m.Run() }
func main() { // Set up logging for CLI log.SetPrefix("") log.SetFlags(0) // Remove the timestamp // Connect to redis err := redisInit() if err != nil { log.Println("Connecting to redis failed", err) } app := cli.NewApp() app.Name = "pixlserv" app.Usage = "transform and serve images" app.Version = "1.0" app.Commands = []cli.Command{ { Name: "run", Usage: "Runs the server (run [config-file])", Action: func(c *cli.Context) { // Set up logging for server log.SetPrefix("[pixlserv] ") if len(c.Args()) < 1 { log.Println("You need to provide a path to a config file") return } configFilePath := c.Args().First() // Initialise configuration err := configInit(configFilePath) if err != nil { log.Println("Configuration reading failed:", err) return } log.Printf("Running with config: %+v", Config) // Initialise authentication err = authInit() if err != nil { log.Println("Authentication initialisation failed:", err) return } // Initialise storage err = storageInit() if err != nil { log.Println("Storage initialisation failed:", err) return } // Run the server m := martini.Classic() if Config.throttlingRate > 0 { m.Use(throttler(Config.throttlingRate)) } m.Use(func(res http.ResponseWriter, req *http.Request) { if uploadURLRe.MatchString(req.URL.Path) { // The upload handler returns JSON res.Header().Set("Content-Type", "application/json") } }) m.Get("/", func() string { return "It works!" }) m.Get("/((?P<apikey>[A-Z0-9]+)/)?image/:parameters/**", transformationHandler) m.Post("/((?P<apikey>[A-Z0-9]+)/)?upload", binding.MultipartForm(UploadForm{}), uploadHandler) go m.Run() // Wait for when the program is terminated ch := make(chan os.Signal) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) <-ch // Clean up redisCleanUp() storageCleanUp() }, }, { Name: "api-key", Usage: "Manages API keys", Subcommands: []cli.Command{ { Name: "add", Usage: "Adds a new one", Action: func(c *cli.Context) { key, err := generateKey() if err != nil { log.Println("Adding a new API key failed, please try again") return } log.Println("Key added:", key) }, }, { Name: "info", Usage: "Shows information about a key (info [key])", Action: func(c *cli.Context) { if len(c.Args()) < 1 { log.Println("You need to provide an existing key") return } key := c.Args().First() permissions, err := infoAboutKey(key) if err != nil { log.Println(err.Error()) return } log.Println("Key:", key) log.Println("Permissions:", permissions) }, }, { Name: "list", Usage: "Shows all keys", Action: func(c *cli.Context) { keys, err := listKeys() if err != nil { log.Println("Retrieving the list of all keys failed") return } log.Println("Keys:", keys) }, }, { Name: "modify", Usage: "Modifies permissions for a key (modify [key] [add/remove] [" + authPermissionsOptions() + "])", Action: func(c *cli.Context) { if len(c.Args()) < 3 { log.Println("You need to provide an existing key, operation and a permission") return } key := c.Args().First() err := modifyKey(key, c.Args()[1], c.Args()[2]) if err != nil { log.Println(err.Error()) return } log.Println("The key has been updated") }, }, { Name: "remove", Usage: "Removes an existing key (remove [key])", Action: func(c *cli.Context) { if len(c.Args()) < 1 { log.Println("You need to provide an existing key") return } err := removeKey(c.Args().First()) if err != nil { log.Println(err.Error()) return } log.Println("The key was successfully removed") }, }, }, }, } app.Run(os.Args) }
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 {} }