Exemple #1
0
func main() {
	LoadDatabase()
	StartAutoSave()

	m := martini.Classic()

	// API endpoints
	m.Get("/app/report/:host", GetReports)
	m.Post("/app/report", binding.Bind(InboundReport{}), FileReport)
	m.Get("/app/suggest/:prefix", SuggestHosts)

	// API endpoints for report actions
	m.Post("/app/update/:reportID/ack", binding.Bind(ActionMeta{}), Acknowledge)
	m.Post("/app/update/:reportID/fixed", binding.Bind(ActionMeta{}), Fixed)
	m.Post("/app/update/:reportID/reject", binding.Bind(ActionMeta{}), Reject)
	m.Post("/app/update/:reportID/delete", binding.Bind(ActionMeta{}), Delete)

	// Serve up the report page
	m.Get("/report/:host", func(req *http.Request, resp http.ResponseWriter) {
		http.ServeFile(resp, req, "public/report.html")
	})

	m.Get("/test", func() string { return "test successful" })

	m.Run()
}
Exemple #2
0
func (h *Httpd) Run() {
	m := martini.Classic()
	m.Get("/", func() string { return "Hello, I'm Takosan!!1" })
	m.Post("/notice", binding.Bind(Param{}), messageHandler)
	m.Post("/privmsg", binding.Bind(Param{}), messageHandler)
	m.RunOnAddr(fmt.Sprintf("%s:%d", h.Host, h.Port))
}
Exemple #3
0
func main() {

	// Initialize
	m := martini.Classic()

	// Connect to mongo
	m.Use(middlewares.Connect())

	// Templating support
	m.Use(middlewares.Templates())

	// Routes

	m.Get("/", func(r render.Render) {
		r.Redirect("/available")
	})

	m.Group("/available", func(r martini.Router) {
		r.Get("", available.List)
		r.Get("/new", available.New)
		r.Get("/:_id", available.Edit)
		r.Post("", binding.Bind(models.AvailableTopic{}), available.Create)
		r.Post("/:_id", binding.Bind(models.AvailableTopic{}), available.Update)
		r.Delete("/:_id", available.Delete)
	})

	// Start listening
	m.Run()
}
Exemple #4
0
func main() {
	var host string
	var port int
	flag.StringVar(&host, "host", "", "The address to bind to")
	flag.IntVar(&port, "port", 9999, "The port to listen at")

	m := martini.Classic()
	m.Use(func(c martini.Context, w http.ResponseWriter) {
		c.MapTo(encoder.JsonEncoder{PrettyPrint: false}, (*encoder.Encoder)(nil))
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
	})

	m.Get("/users", GetUsers)
	m.Post("/users", binding.Bind(User{}), CreateUser)
	m.Get("/users/:id", GetUser)
	m.Delete("/users/:id", DeleteUser)
	m.Get("/users/:id/teams", GetUserTeams)
	m.Get("/users/:id/goals", GetUserGoals)

	m.Get("/teams", GetTeams)
	m.Post("/teams", binding.Bind(Team{}), CreateTeam)
	m.Get("/teams/:id", GetTeam)
	m.Delete("/teams/:id", DeleteTeam)

	m.Put("/users/:uid/teams/:tid", AddUserToTeam)
	m.Delete("/users/:uid/teams/:tid", DeleteUserFromTeam)

	m.Post("/goals", binding.Bind(Goal{}), CreateGoal)
	m.Get("/goals/:id", GetGoal)
	m.Post("/goals/:id", binding.Bind(GoalCompleteParams{}), CompleteGoal)

	log.Fatal(http.ListenAndServe(":8080", m))
	m.Run()
}
Exemple #5
0
func Routes() http.Handler {
	// Middlewares are setup and run before each incoming request
	// the ones named like *Provider provide singleton instances
	// of injectable objects. For instance appx, logger, appengine context
	// can be injected in our routes handlers (a.k.a controllers)
	router := martini.Classic()

	router.Use(render.Renderer())
	router.Use(middlewares.AppengineContextProvider)
	router.Use(middlewares.LoggerProvider)
	router.Use(middlewares.AppxProvider)

	router.Post("/login", binding.Bind(controllers.LoginForm{}), controllers.Login)

	router.Group("/account", func(r martini.Router) {
		r.Post("/registerDropbox", binding.Bind(controllers.RegisterDropboxForm{}), controllers.RegisterDropbox)
		r.Post("/update", binding.Bind(controllers.AccountUpdateForm{}), controllers.UpdateAccount)

		r.Group("/dropbox", func(r martini.Router) {
			r.Post("/init", controllers.DropboxInit)
			r.Post("/delta", controllers.DropboxDelta)
		}, middlewares.ExternalServiceAuthorizationProvider)

		r.Group("/trails", func(r martini.Router) {
			r.Get("/next_evaluation", controllers.TrailNextEvaluation)
			r.Patch("/:trail_id/like", controllers.TrailLike)
			r.Patch("/:trail_id/dislike", controllers.TrailDislike)
			r.Get("/tags", controllers.Tags)
			r.Get("/tags/:tag_id", controllers.TagTrails)
		})
	}, middlewares.AuthorizationAccountProvider)

	return router
}
Exemple #6
0
func (self *oprPrevSeasonRankCom) Start(peer netfw.IPeer) {

	m := peer.(martinihttp.IMartiniAcceptor).GetInterface()

	m.Get("/seasonrank", sessionauth.LoginRequired, binding.Bind(queryZone{}), func(r render.Render, msg queryZone) {

		var zones []zoneInfo

		dbopr.IterateShowDB(func(name, showname string) {
			zones = append(zones, zoneInfo{
				Name:     name,
				ShowName: showname,
			})
		})

		r.HTML(200, "index", nil)
		r.HTML(200, "seasonrank", zones)

	})

	m.Post("/rankdata", sessionauth.LoginRequired, binding.Bind(queryZone{}), func(r render.Render, msg queryZone) {

		res, err := dbopr.ExecuteSQL(msg.Zone, &dbLastSeason{}, "select $FIELD_NAME$ from tb_last_season")
		if err != nil {
			r.Data(200, []byte(err.Error()))
			return
		}

		r.JSON(200, res)

	})

}
// Route return the route handler for this
func (s ServiceRegistryWebService) Route() martini.Router {
	r := martini.NewRouter()
	r.Group("/apiversions/", func(r martini.Router) {
		r.Get("", s.getAPIVersions)
		r.Post("", binding.Bind(common.APIVersion{}), s.createAPIVersion)
	})

	r.Group("/apiversions/:version/", func(r martini.Router) {
		r.Get("", s.getAPIVersion)
		r.Get("services/", s.getAPIServices)
		r.Post("services/", binding.Bind(common.ServiceVersion{}), s.createAPIService)
	})

	r.Group("/services/", func(r martini.Router) {
		r.Get("", s.getServices)
		r.Post("", binding.Bind(common.ServiceDefinition{}), s.createService)
		r.Delete(":service/", s.dropService)
	})

	r.Group("/services/:service/versions", func(r martini.Router) {
		r.Get("", s.getServiceVersions)
		r.Post("", binding.Bind(common.ServiceVersion{}), s.createServiceVersion)
	})

	r.Group("/services/:service/:version/hosts/", func(r martini.Router) {
		r.Get("", s.getServiceHosts)
		r.Post("", binding.Bind(common.ServiceHost{}), s.attachServiceHost)
	})

	return r
}
Exemple #8
0
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()
}
Exemple #9
0
func main() {

	config, err := config.Load()
	if err != nil {
		log.Fatal(err)
	}

	fishhubService, err := fishhub.NewService(config.MongoURL)
	if err != nil {
		log.Fatal(err)
	}

	sessionService, err := session.NewService(config.MongoURL)
	if err != nil {
		log.Fatal(err)
	}

	store := sessions.NewCookieStore([]byte("@!#$%^&*"))

	m := martini.Classic()

	m.Map(fishhubService)
	m.Map(sessionService)

	m.Use(sessions.Sessions("go_session", store))

	// Setup routes
	m.Get("/", home)

	m.Group("/users", func(r martini.Router) {
		r.Post("", binding.Bind(UserForm{}), NewUser)
		r.Get("/:id", GetUser)
		r.Put("/update/:id", UpdateUser)
		r.Delete("/delete/:id", DeleteUser)
	})

	m.Group("/login", func(r martini.Router) {
		r.Post("", binding.Bind(LoginForm{}), CheckCredential)
	})

	m.Handlers(
		render.Renderer(render.Options{
			Delims: render.Delims{"<%", "%>"},
		}),
		martini.Logger(),
		martini.Static("public"),
	)

	m.NotFound(func(r render.Render) {
		r.HTML(404, "404", nil)
	})

	err = http.ListenAndServe(":"+config.Port, m)
	if err != nil {
		log.Fatal(err)
	}

}
func SetupRoutes(db *mgo.Database, m *martini.ClassicMartini) {
	m.Group("/oauth", func(r martini.Router) {
		r.Get("/register/:type", modules.Register)
		r.Get("/github", binding.Bind(models.GithubOAuth{}), modules.GithubOAuth)
	})

	m.Group("/api/user", func(r martini.Router) {
		r.Put("/", binding.Bind(models.User{}), api.RegisterUser)
	})
}
Exemple #11
0
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)
}
Exemple #12
0
func registerRoutes(server *martini.ClassicMartini) {
	// Box
	server.Post("/boxes", binding.Bind(request.CreateRequest{}), boxCreate)
	server.Put("/boxes/:name", binding.Bind(request.DeployRequest{}), boxDeploy)
	server.Get("/boxes", boxList)
	server.Get("/boxes/:name", boxInspect)
	server.Delete("/boxes/:name", boxDelete)

	// Domain
	server.Post("/boxes/:name/domain", binding.Bind(request.Domain{}), domainAdd)
	server.Delete("/boxes/:name/domain/:domain", domainDelete)
}
Exemple #13
0
func main() {
	config := config.New()
	config.Load("config.json")
	cfbase := config.GetString("database", "sqlite3")
	cfconn := config.GetString("connection", "./app.db")
	db, err := gorm.Open(cfbase, cfconn)
	checkErr(err, "Database connection failed")
	db.AutoMigrate(&models.Blog{})
	db.AutoMigrate(&models.Classify{})
	defer db.Close()

	admin := &fun.Admins{Account: config.GetString("web_account", "admin"), Password: config.GetString("web_password", "admin")}

	jade := gojade.New()
	jade.ViewPath = "./jade"
	jade.RegisterFunction("date", fun.Date)
	jade.RegisterFunction("dateformat", fun.DateFormat)
	jade.RegisterFunction("compare", fun.Compare)
	jade.RegisterFunction("compare_not", fun.CompareNot)
	jade.RegisterFunction("substr", fun.Substr)
	jade.RegisterFunction("subtext", fun.Subtext)
	jade.RegisterFunction("img", fun.Img)
	jade.RegisterFunction("html2str", fun.HTML2str)
	jade.RegisterFunction("str2html", fun.Str2html)
	jade.RegisterFunction("htmlquote", fun.Htmlquote)
	jade.RegisterFunction("htmlunquote", fun.Htmlunquote)
	jade.RegisterFunction("map_get", fun.MapGet)

	m := martini.Classic()
	m.Map(db)
	m.Map(jade)
	m.Map(admin)
	m.Use(martini.Static("static"))
	m.Get("/", controllers.Home)
	m.Get("/:tag.html", controllers.Tag)
	m.Get("/view/:id.html", controllers.View)
	m.Get("/_login", controllers.Login)
	m.Get("/_logout", controllers.Logout)
	m.Get("/_add", controllers.Check, controllers.Create)
	m.Get("/_class", controllers.Check, controllers.Classify)
	m.Get("/_edit/:id", controllers.Check, controllers.Edit)
	m.Get("/_delete/:id", controllers.Check, controllers.Delete)

	m.Post("/_login", binding.Bind(models.Admin{}), controllers.LoginPost)
	m.Post("/_add", binding.Bind(models.Blog{}), controllers.CreatePost)
	m.Post("/_class", binding.Bind(models.Classify{}), controllers.ClassifyPost)
	m.Post("/_edit/:id", binding.Bind(models.Blog{}), controllers.UpdatePost)

	m.NotFound(controllers.NotFound)
	m.Run()
}
Exemple #14
0
func main() {
	m := martini.Classic()

	m.Use(cors.Allow(&cors.Options{
		AllowOrigins:     []string{"*"},
		AllowMethods:     []string{"PUT", "PATCH", "GET", "POST", "OPTIONS"},
		AllowHeaders:     []string{"Origin", "content-type"},
		ExposeHeaders:    []string{"Content-Length"},
		AllowCredentials: true,
	}))

	session, err := mgo.Dial("localhost")

	if err != nil {
		panic(err)
	}

	defer session.Close()

	m.Map(session)

	m.Group("/foods", func(r martini.Router) {
		r.Get("", GetFood)
		r.Get("/:id", GetFood)
		r.Get("/queries/:name", GetFoodByName)
		r.Post("/new", binding.Bind(d.Food{}), NewFood)
		r.Put("/update/:id", binding.Bind(d.Food{}), UpdateFood)
		r.Delete("/delete/:id", DeleteFood)
	})

	m.Group("/recipes", func(r martini.Router) {
		r.Get("", GetRecipe)
		r.Get("/:id", GetRecipe)
		r.Post("", binding.Bind(Recipe{}), NewRecipe)
		r.Put("/update/:id", binding.Bind(Recipe{}), UpdateRecipe)
		r.Delete("/delete/:id", DeleteRecipe)
	})

	m.Get("/foodGroup", func() []byte {
		foodGroupDB := session.DB("CNF").C("foodGroup")
		query := foodGroupDB.Find(nil)
		var result []d.FoodGroup
		query.All(&result)
		b, _ := json.Marshal(result)
		return b
	})

	m.Run()
}
Exemple #15
0
func main() {
	m := martini.Classic()

	if envGet(ENV_RESTRICT_DOMAINS) == "" {
		m.Get("/qr", binding.Bind(meddler.Payload{}), presentQRCode)
		m.Post("/qr", binding.Bind(meddler.Payload{}), presentQRCode)
	}

	m.Get("/drive/qr", binding.Bind(meddler.Payload{}), googleDriveDomainRestrictedQRCode)
	m.Post("/drive/qr", binding.Bind(meddler.Payload{}), googleDriveDomainRestrictedQRCode)

	// m.Post("/gen", GenerateKeySet)

	m.Run() // m.RunOnAddr(envAddrInfo.ConnectionString())
}
func (us UserService) Register(router martini.Router) {
	utils.Log.Debug("Registering UserService!")

	router.Group("/users", func(rtr martini.Router) {
		rtr.Post("", PreventReauth, binding.Bind(models.User{}), us.Create)
		rtr.Post("/update", EnsureAuth, binding.Bind(models.User{}), us.Update)
	})

	router.Get("/signout", us.SignOut)
	router.Get("/signup", PreventReauth, us.SignUp)
	router.Get("/signin", PreventReauth, us.SignIn)
	router.Get("/dashboard", EnsureAuth, us.Dashboard)
	router.Get("/settings/edit", EnsureAuth, us.Edit)
	router.Get("/settings/edit/:category", EnsureAuth, us.Edit)
	router.Get("/wakatime/sync", EnsureAuth, us.SyncHeartbeats)
}
func EnsureAuth(r martini.Router, mainDb *d.MainDb) martini.Router {

	r.Get("/", func(r render.Render, prms martini.Params, req *http.Request) {
		flashMessage, fType := flash.GetMessage()
		query := req.URL.Query()
		result := map[string]interface{}{
			fmt.Sprintf("flash_%v", fType): flashMessage,
			"from": query.Get("from"),
		}

		r.HTML(200, "login", AddCurrentUser(result, req, mainDb), render.HTMLOptions{Layout: "base"})
	})

	r.Post("/", binding.Bind(user{}), func(postedUser user, r render.Render, req *http.Request, w http.ResponseWriter) {
		userData, err := mainDb.Users.LoginUser(postedUser.LoginName, postedUser.Password)
		if err != nil {
			log.Printf("AUTH user %+v not found: %v", postedUser, err)
			flash.SetMessage("К сожалению, пользователь с такими данными не найден.", "error")
			r.Redirect(AUTH_URL)
			return
		} else {
			log.Printf("AUTH found user data: %v, %v, %v", userData.UserId, userData.UserName, userData.Auth)
		}
		user := NewUser(userData)
		StartAuthSession(user, w)
		redirect := req.URL.Query().Get(REDIRECT_PARAM)
		if redirect == "" {
			redirect = DefaultUrlMap.GetDefaultUrl(user.BelongsToCompany())
		}
		http.Redirect(w, req, redirect, 302)
	})
	return r
}
Exemple #18
0
func apiHandler(router *Router) http.Handler {
	r := martini.NewRouter()
	m := martini.New()
	m.Use(martini.Logger())
	m.Use(martini.Recovery())
	m.Use(render.Renderer())
	m.Action(r.Handle)
	m.Map(router)

	r.Post("/routes", binding.Bind(strowger.Route{}), createRoute)
	r.Put("/routes", binding.Bind(strowger.Route{}), createOrReplaceRoute)
	r.Get("/routes", getRoutes)
	r.Get("/routes/:route_type/:route_id", getRoute)
	r.Delete("/routes/:route_type/:route_id", deleteRoute)
	return m
}
Exemple #19
0
func main() {
	m := martini.Classic()

	m.Use(martini.Static("public"))

	m.Use(render.Renderer(render.Options{
		Layout:     "layout",
		Extensions: []string{".tmpl.html"},
	}))

	var opts db.Options
	level, err := leveldb.Open("database/messageDB", &opts)
	if err != nil {
		panic(err)
	}
	defer level.Close()

	m.Map(level)

	m.Get("/", Index)
	m.Get("/add", Add)
	m.Post("/create", binding.Bind(Message{}), Create)

	m.Run()
}
Exemple #20
0
//--------------------------------------
//文件管理逻辑
//
//KindEditor提交参数:
//dir{"image", "flash", "media", "file"},默认"image"
//path,默认"",格式:"2014年","2014年1月","201401-<filename>"
//order,默认"name"
//
//返回给KindEditor的参数:
//moveup_dir_path": "",
//"current_dir_path": "",
//"current_url": "/ke4/php/../attached/",
//"total_count": 5,
//"file_list": [
//
//{
//    "is_dir": false,
//    "has_file": false,
//    "filesize": 208736,
//    "is_photo": true,
//    "filetype": "jpg",
//    "filename": "1241601537255682809.jpg",
//    "datetime": "2011-08-02 15:32:43"
//},
//{
//    "is_dir": true,
//    "has_file": (file.listFiles() != null),
//    "filesize": 0L,
//    "is_photo": false,
//    "filetype": "",
//    "filename": file.getName(),
//    "datetime": "2011-08-02 15:32:43"
//},
//--------------------------------------
//martini handler
func ListFilesHandlers() []martini.Handler {
	var bind = binding.Bind(ListReqData{})
	var listHandler = func(data ListReqData, w http.ResponseWriter, r *http.Request) {
		if strings.ToUpper(data.Dir) != "IMAGE" {
			data.Err(w, "dir should be IMAGE")
			return
		}
		//根据path建立KindList
		list := &KindList{CurrentDirPath: strings.TrimSuffix(data.Path, "/")}
		switch length := len([]rune(list.CurrentDirPath)); length {
		case 0: //""
			listYears(r, list)
		case 5: //"2014年, 2014年"
			if err := listMonths(r, list); err != nil {
				data.Err(w, err.Error())
				return
			}
		case 7, 8: //"2014年4月"
			if err := listFiles(&data, list); err != nil {
				data.Err(w, err.Error())
				return
			}
		default:
			data.Err(w, `Path wrong:`+data.Path)
			return
		}
		io.WriteString(w, data.Callback+"(")
		resJson(w, list)
		io.WriteString(w, ")")
	}
	return []martini.Handler{bind, listHandler}
}
Exemple #21
0
func main() {
	m := martini.Classic()
	m.Use(render.Renderer(render.Options{
		Directory:  "templates",
		Extensions: []string{".tmpl", ".html"},
		Charset:    "UTF-8",
		Funcs: []template.FuncMap{
			{
				"equal": func(args ...interface{}) bool {
					return args[0] == args[1]
				},
			},
		},
	}))
	store := sessions.NewCookieStore([]byte("secret123"))
	m.Use(sessions.Sessions("my_session", store))
	m.Get("/", youth)
	m.Get("/firtConfirm", firtConfirm)
	m.Post("/firtConfirm", binding.Form(model.User{}), firtConfirmPost)
	m.Post("/userSiginCheck", binding.Bind(SiginIfo{}), userSiginCheck)
	m.Get("/userInforEdit", userInforEdit)
	m.Post("/userInforEdit", binding.Form(model.User{}), userInforEditPost)
	m.Get("/editReruenInfo/:status", editReruenInfo)
	m.Run()
}
Exemple #22
0
func (web *MailWeb) initHandlers() {
	// Public Handlers
	web.martini.Get("/", web.welcome)
	web.martini.Post("/", binding.Bind(auth.WatneyUser{}), web.authenticate)
	// Reserved for martini sessionauth forwarding, in case the session timed out
	web.martini.Get("/sessionTimeout", web.timeout)

	// Private Handlers
	web.martini.Get("/logout", sessionauth.LoginRequired, web.logout)
	web.martini.Get("/main", sessionauth.LoginRequired, web.main)

	web.martini.Post("/mailContent", sessionauth.LoginRequired, web.mailContent)
	web.martini.Post("/mails", sessionauth.LoginRequired, web.mails)
	web.martini.Post("/poll", sessionauth.LoginRequired, web.poll)
	web.martini.Post("/sendMail", sessionauth.LoginRequired, web.sendMail)
	web.martini.Post("/moveMail", sessionauth.LoginRequired, web.moveMail)
	web.martini.Post("/trashMail", sessionauth.LoginRequired, web.trashMail)
	web.martini.Post("/updateFlags", sessionauth.LoginRequired, web.updateFlags)
	web.martini.Post("/userInfo", sessionauth.LoginRequired, web.userInfo)

	// Static content
	web.martini.Use(martini.Static("static/resources/libs/",
		martini.StaticOptions{Prefix: "/libs/"}))
	web.martini.Use(martini.Static("static/resources/js/",
		martini.StaticOptions{Prefix: "/js/"}))
	web.martini.Use(martini.Static("static/resources/css/",
		martini.StaticOptions{Prefix: "/css/"}))
}
Exemple #23
0
func main() {
	m := martini.Classic()
	m.Map(SetupDB())
	m.Use(render.Renderer())

	m.Get("/", func() string {
		return "Hello!"
	})
	m.Get("/todos", TodoIndex)
	m.Post("/todos", binding.Bind(Todo{}), TodoCreate)
	m.Get("/todos/:id", TodoShow)
	m.Patch("/todos/:id", binding.Bind(Todo{}), TodoUpdate)
	m.Put("/todos/:id", binding.Bind(Todo{}), TodoUpdate)
	m.Delete("/todos/:id", TodoDestroy)

	m.Run()
}
Exemple #24
0
func main() {
	if envKeySet.PublicKey == "" {
		errorPrint("publicKey not set. Please set %s in your env.\n", envKeyAlias.PubKeyAlias)
		return
	}

	if envKeySet.PrivateKey == "" {
		errorPrint("privateKey not set. Please set %s in your env.\n", envKeyAlias.PrivKeyAlias)
		return
	}

	m := martini.Classic()

	m.Get("/", requestDownloadForm)
	m.Get("/gif", requestDownloadFormGif)
	m.Get("/webm", requestDownloadFormWebm)
	m.Get("/png", requestDownloadFormPng)
	m.Get("/head", binding.Bind(downloader.DownloadItem{}), downloader.HeadGet)
	m.Get("/download", binding.Bind(downloader.DownloadItem{}), download)

	m.Post("/extrict/gif", binding.Bind(downloader.DownloadItem{}), extrictGif)
	m.Post("/extrict/mp4", binding.Bind(downloader.DownloadItem{}), extrictMp4)
	m.Post("/extrict/webm", binding.Bind(downloader.DownloadItem{}), extrictWebm)
	m.Post("/extrict/png", binding.Bind(downloader.DownloadItem{}), extrictPng)
	m.Post("/download", binding.Bind(downloader.DownloadItem{}), download)

	m.Run()
}
Exemple #25
0
func main() {
	store := sessions.NewCookieStore([]byte("secret123"))
	dbmap = initDb()

	m := martini.Classic()
	m.Use(render.Renderer())

	// Default our store to use Session cookies, so we don't leave logged in
	// users roaming around
	store.Options(sessions.Options{
		MaxAge: 0,
	})
	m.Use(sessions.Sessions("my_session", store))
	m.Use(sessionauth.SessionUser(GenerateAnonymousUser))
	sessionauth.RedirectUrl = "/login"
	sessionauth.RedirectParam = "index"

	m.Get("/", func(r render.Render) {
		r.HTML(200, "index", nil)
	})

	m.Get("/login", func(r render.Render) {
		r.HTML(200, "login", nil)
	})

	m.Post("/new-login", binding.Bind(MyUserModel{}), func(session sessions.Session, postedUser MyUserModel, r render.Render, req *http.Request) {
		// You should verify credentials against a database or some other mechanism at this point.
		// Then you can authenticate this session.
		user := MyUserModel{}
		err := dbmap.SelectOne(&user, "SELECT * FROM users WHERE username = $1 and password = $2", postedUser.Username, postedUser.Password)
		if err != nil {
			r.Redirect(sessionauth.RedirectUrl)
			return
		} else {
			err := sessionauth.AuthenticateSession(session, &user)
			if err != nil {
				r.JSON(500, err)
			}

			params := req.URL.Query()
			redirect := params.Get(sessionauth.RedirectParam)
			r.Redirect(redirect)
			return
		}
	})

	m.Get("/private", sessionauth.LoginRequired, func(r render.Render, user sessionauth.User) {
		r.HTML(200, "private", user.(*MyUserModel))
	})

	m.Get("/logout", sessionauth.LoginRequired, func(session sessions.Session, user sessionauth.User, r render.Render) {
		sessionauth.Logout(session, user)
		r.Redirect("/")
	})

	m.Run()
}
Exemple #26
0
func main() {
	if envKeySet.PublicKey == "" {
		errorPrint("publicKey not set. Please set %s in your env.\n", envKeyAlias.PubKeyAlias)
		return
	}

	if envKeySet.PrivateKey == "" {
		errorPrint("privateKey not set. Please set %s in your env.\n", envKeyAlias.PrivKeyAlias)
		return
	}

	m := martini.Classic()

	m.Get("/qr", binding.Bind(meddler.Payload{}), presentQRCode)
	m.Post("/qr", binding.Bind(meddler.Payload{}), presentQRCode)

	m.RunOnAddr(envAddrInfo.ConnectionString())
}
Exemple #27
0
func main() {
	m := martini.Classic()

	m.Use(render.Renderer(render.Options{
		Layout: "_layout",
	}))

	m.Use(secure.Secure(secure.Options{
		SSLRedirect:     true,
		SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
	}))
	store := sessions.NewCookieStore([]byte(os.Getenv("COOKIE_SECRET")))
	m.Use(sessions.Sessions("the_session", store))
	m.Use(sessionauth.SessionUser(GenerateAnonymousUser))

	/** Main router **/

	m.Get("/", sessionauth.LoginRequired, cameraList)
	m.Get("/camimage", sessionauth.LoginRequired, cameraImage)

	/** Login Handling **/

	m.Get("/login", func(r render.Render) {
		r.HTML(200, "login", nil, render.HTMLOptions{
			Layout: "_login_layout",
		})
	})

	m.Post("/login", binding.Bind(User{}), func(session sessions.Session, postedUser User, r render.Render, req *http.Request) {

		// if not logged in
		if postedUser.Passcode != "" && postedUser.Passcode == os.Getenv("WEB_PASSCODE") {
			user := &User{}
			err := sessionauth.AuthenticateSession(session, user)
			if err != nil {
				r.Text(500, "Error authenticating session")
				return
			}

			params := req.URL.Query()
			redirect := params.Get(sessionauth.RedirectParam)
			r.Redirect(redirect)
			return
		} else {
			r.Redirect(sessionauth.RedirectUrl)
			return

		}
	})

	m.Get("/logout", sessionauth.LoginRequired, func(session sessions.Session, user sessionauth.User, r render.Render) {
		sessionauth.Logout(session, user)
		r.Redirect("/")
	})

	m.Run()
}
Exemple #28
0
func main() {
	m := martini.Classic()
	m.Use(render.Renderer())

	m.Get("/", func(r render.Render) {
		r.JSON(200, map[string]interface{}{"hello": "world"})
	})

	m.Get("/person", func(r render.Render) {
		r.JSON(200, Person{
			Name: "newegg",
			Age:  30,
			Card: GetCard(),
		})
	})

	//get route param
	m.Get("/order/:orderid", func(params martini.Params) string {
		return "this.is " + params["orderid"]
	})

	//get query string
	m.Get("/product", func(r *http.Request) string {
		qs := r.URL.Query()
		return qs.Get("productid")
	})

	//反序列化json
	m.Post("/card", binding.Bind(PersonCard{}), func(card PersonCard) string {
		return fmt.Sprintf("CardId: %d", card.CardId)
	})

	//读取并输出json, martini会通过Injector来匹配HandlerFunc的参数类型
	m.Put("/card", binding.Bind(PersonCard{}), func(r render.Render, card PersonCard) {
		r.JSON(http.StatusOK, Person{
			Name: "newegg",
			Age:  30,
			Card: GetCard(),
		})
	})

	//m.Run()
	http.ListenAndServe(":8060", m)
}
Exemple #29
0
func main() {
	var err error

	sqlConnection = "doug:[email protected](127.0.0.1:3306)/martini-gorm?parseTime=True"

	db, err = gorm.Open("mysql", sqlConnection)

	if err != nil {
		panic(err)
		return
	}

	m := martini.Classic()

	m.Use(render.Renderer())
	m.Get("/", func(r render.Render) {
		var retData struct {
			Items []Item
		}

		db.Find(&retData.Items)

		r.HTML(200, "index", retData)
	})

	m.Get("/item/add", func(r render.Render) {
		var retData struct {
			Item Item
		}

		r.HTML(200, "item_edit", retData)
	})

	m.Post("/item/save", binding.Bind(Item{}), func(r render.Render, i Item) {
		db.Save(&i)
		r.Redirect("/")
	})

	m.Get("/item/edit/:id", func(r render.Render, p martini.Params) {
		var retData struct {
			Item Item
		}

		db.Where("id = ?", p["id"]).Find(&retData.Item)

		r.HTML(200, "item_edit", retData)
	})

	m.Get("/item/remove/:id", func(r render.Render, p martini.Params) {
		var item Item
		db.Where("id = ?", p["id"]).Delete(&item)
		r.Redirect("/")
	})

	m.Run()
}
Exemple #30
0
func init() {

	m := martini.Classic()
	m.Use(render.Renderer(render.Options{IndentJSON: true}))
	m.Use(middleware.AppengineContextProvider)
	m.Use(middleware.AppxProvider)
	m.Use(middleware.RequestLocationProvider)

	m.Post("/login", binding.Bind(model.User{}), handler.LoginHandler)

	m.Group("/posts", func(r martini.Router) {
		r.Post("", binding.Bind(model.Post{}), handler.CreatePostHandler)
		r.Get("", handler.ListPostsHandler)
		r.Get("/:plate", handler.ListPostsByCarPlateHandler)
		r.Put("/:post_id", handler.FlagPostHandler)
	})

	http.Handle("/", m)
}