示例#1
0
func BindArticleApi(m *martini.ClassicMartini) {
	m.Get("/api/article/latest", binding.Form(pagination{}), latestArticlesHandler)
	m.Get("/api/article/hots", binding.Form(pagination{}), latestArticlesHandler)
	m.Get("/api/article/comment", binding.Form(pagination{}), latestArticlesHandler)
	m.Get("/api/article/update", binding.Form(pagination{}), latestArticlesHandler)
	m.Get("/api/article/A:id", articleInfoHandler)
}
示例#2
0
func BindRecordApi(m *martini.ClassicMartini) {
	m.Post("/1/record/new",
		binding.Json(newRecordForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		newRecordHandler)
	m.Get("/1/record/get",
		binding.Form(getRecordForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		getRecordHandler)
	m.Get("/1/record/timeline",
		binding.Form(recTimelineForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		recTimelineHandler)
	m.Get("/1/record/statistics",
		binding.Form(userRecStatForm{}),
		ErrorHandler,
		userRecStatHandler)
	m.Get("/1/leaderboard/list",
		binding.Form(leaderboardForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		leaderboardHandler)
	m.Get("/1/leaderboard/gameList",
		binding.Form(gamelbForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		gamelbHandler,
	)
}
示例#3
0
文件: youth.go 项目: cwen-coder/youth
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()
}
示例#4
0
func main() {
	m := martini.Classic()

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

	m.Use(DB())
	m.Use(martini.Static("/css/"))

	m.Get("/", func(r render.Render, db *mgo.Database) {
		r.HTML(200, "list", All(db))
	})

	m.Post("/", binding.Form(Account{}), func(account Account, r render.Render, db *mgo.Database) {
		db.C("accounts").Insert(account)
		r.HTML(200, "list", All(db))
	})
	
	m.Post("/:accountName", binding.Form(Transaction{}), func(transaction Transaction, r render.Render, db *mgo.Database) {
		db.C("transaction").Insert(transaction)
		r.HTML(200, "display", Fetch(db, params["handle"]))
	}

	m.Get("/:handle", func(params martini.Params, r render.Render, db *mgo.Database) {
		r.HTML(200, "display", Fetch(db, params["handle"]))
	})

	m.Run()
}
示例#5
0
func BindWalletApi(m *martini.ClassicMartini) {
	m.Get("/1/wallet/get",
		binding.Form(walletForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		getWalletHandler)
	m.Get("/1/wallet/balance",
		binding.Form(walletForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		balanceHandler)
	m.Get("/1/wallet/newaddr",
		binding.Form(walletForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		newAddrHandler)
	m.Post("/1/wallet/send",
		binding.Json(txForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		txHandler)
	m.Get("/1/wallet/txs",
		binding.Form(addrTxsForm{}),
		addrTxsHandler)
}
示例#6
0
文件: main.go 项目: tpiha/barecv
// Main function
func main() {
	// Initializa config
	config = &BareCVConfig{}
	config.Load("../config.json")

	// Initizalize database
	db = InitDb()

	// Initialize Martini
	m = martini.Classic()

	// Render html templates from templates directory
	m.Use(render.Renderer(render.Options{
		Extensions: []string{".html"},
		Layout:     "layout",
		Funcs: []template.FuncMap{
			{
				"unescaped": func(args ...interface{}) template.HTML {
					log.Printf("[main] unescaped: %s", args[0].(string))
					urlStr, _ := url.QueryUnescape(args[0].(string))
					return template.HTML(urlStr)
				},
			},
		},
	}))

	// Initializes Google auth
	InitGoogle()

	// GET methods
	m.Get("/", Home)
	m.Get("/dashboard", oauth2.LoginRequired, Dashboard)
	m.Get("/cv/:username", oauth2.LoginRequired, ShowPrivate)
	m.Get("/cv", binding.Form(ProfileForm{}), oauth2.LoginRequired, CV)
	m.Get("/sections", oauth2.LoginRequired, Sections)
	m.Get("/sections/new/:type", oauth2.LoginRequired, SectionsNew)
	m.Get("/sections/delete/:section_id", oauth2.LoginRequired, SectionsDelete)
	m.Get("/sections/:type/:section_id", oauth2.LoginRequired, SectionsUpdate)
	m.Get("/account", oauth2.LoginRequired, Account)
	m.Get("/account-delete", oauth2.LoginRequired, AccountDelete)
	m.Get("/account-redirect", oauth2.LoginRequired, AccountRedirect)
	m.Get("/generate-pdf", oauth2.LoginRequired, GeneratePDF)
	m.Get("/settings", oauth2.LoginRequired, Settings)
	m.Get("/:hash", ShowHash)

	// POST methods
	m.Post("/cv-save", binding.Form(ProfileForm{}), oauth2.LoginRequired, Save)
	m.Post("/cv-save-social", binding.Form(SocialNetworksForm{}), oauth2.LoginRequired, SaveSocial)
	m.Post("/account-save", binding.Form(UsernameForm{}), oauth2.LoginRequired, AccountSave)
	m.Post("/sections/new/:type", oauth2.LoginRequired, SectionsPost)
	m.Post("/sections/:type/:section_id", oauth2.LoginRequired, SectionsPost)
	m.Post("/sections/reorder", oauth2.LoginRequired, Reorder)
	m.Post("/settings", binding.Form(SettingsForm{}), oauth2.LoginRequired, SettingsSave)

	// Run server
	// m.RunOnAddr(":8080")
	m.Run()
}
示例#7
0
func BindTaskApi(m *martini.ClassicMartini) {
	m.Get("/admin/task/list", binding.Form(tasklistForm{}), adminErrorHandler, tasklistHandler)
	m.Get("/admin/task/timeline", binding.Form(userTaskForm{}), adminErrorHandler, userTaskHandler)
	//m.Get("/admin/task/timeline", binding.Form(taskTimelineForm{}), adminErrorHandler, taskTimelineHandler)
	m.Post("/admin/task/auth", binding.Json(taskAuthForm{}), adminErrorHandler, taskAuthHandler)
	m.Options("/admin/task/auth", optionsHandler)
	m.Post("/admin/task/auth_list", binding.Json(taskAuthListForm{}), adminErrorHandler, taskAuthListHandler)
	m.Options("/admin/task/auth_list", optionsHandler)
}
示例#8
0
func BindArticleApi(m *martini.ClassicMartini) {
	m.Get("/admin/article/info", binding.Form(articleInfoForm{}), adminErrorHandler, articleInfoHandler)
	m.Get("/admin/article/list", binding.Form(articleListForm{}), adminErrorHandler, articleListHandler)
	m.Get("/admin/article/timeline", binding.Form(articleListForm{}), adminErrorHandler, articleTimelineHandler)
	m.Get("/admin/article/comments", binding.Form(articleListForm{}), adminErrorHandler, articleCommentsHandler)
	m.Options("/admin/article/post", articlePostOptionsHandler)
	m.Post("/admin/article/post", binding.Json(postForm{}), adminErrorHandler, articlePostHandler)
	m.Post("/admin/article/delete", binding.Json(delArticleForm{}), adminErrorHandler, delArticleHandler)
	m.Get("/admin/article/search", binding.Form(articleSearchForm{}), adminErrorHandler, articleSearchHandler)
	m.Post("/admin/article/update", binding.Json(articleUpdateForm{}), adminErrorHandler, articleUpdateHandler)
}
示例#9
0
func BindUeditorApi(m *martini.ClassicMartini) {
	m.Get("/ueditor/controller",
		binding.Form(ueditorForm{}),
		ueditorHandler)
	m.Post("/ueditor/controller",
		binding.Form(ueditorForm{}),
		ueditorHandler)
	m.Options("/ueditor/controller",
		binding.Form(ueditorForm{}),
		ueditorHandler)
}
示例#10
0
func BindArticleApi(m *martini.ClassicMartini) {
	m.Post("/1/article/new",
		binding.Json(newArticleForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		newArticleHandler)
	m.Post("/1/article/delete",
		binding.Json(deleteArticleForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		deleteArticleHandler)
	m.Post("/1/article/thumb",
		binding.Json(articleThumbForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		articleThumbHandler)
	m.Get("/1/article/is_thumbed",
		binding.Form(articleIsThumbedForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		articleIsThumbedHandler)
	m.Get("/1/article/timelines",
		binding.Form(articleListForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		articleListHandler)
	m.Get("/1/article/get",
		binding.Form(articleInfoForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		articleInfoHandler)
	m.Post("/1/article/comments",
		binding.Json(articleCommentsForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		articleCommentsHandler)
	m.Get("/1/aritcle/thumbList",
		binding.Form(thumbersForm{}),
		thumbersHandler)
	m.Get("/1/article/news",
		binding.Form(articleNewsForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		articleNewsHandler)
}
示例#11
0
func BindTaskApi(m *martini.ClassicMartini) {
	m.Get("/1/tasks/get",
		binding.Form(getTaskForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		getTaskHandler)
	m.Get("/1/tasks/getList",
		binding.Form(getTasksForm{}),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		getTasksHandler)
	m.Get("/1/tasks/getInfo",
		binding.Form(getTaskInfoForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		//loadUserHandler,
		getTaskInfoHandler)
	m.Get("/1/tasks/result",
		binding.Form(getTaskResultForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		//loadUserHandler,
		getTaskResultHandler)
	m.Post("/1/tasks/execute",
		binding.Json(completeTaskForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		completeTaskHandler)
	m.Get("/1/tasks/referrals",
		binding.Form(taskReferralForm{}),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		taskReferralsHandler)
	m.Post("/1/tasks/share",
		binding.Json(taskShareForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		taskShareHandler)
	m.Post("/1/tasks/shared",
		binding.Json(taskSharedForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		taskSharedHandler)
}
示例#12
0
func BindUserApi(m *martini.ClassicMartini) {
	m.Post("/1/user/send_device_token",
		binding.Json(sendDevForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		sendDevHandler)
	m.Post("/1/user/set_push_enable",
		binding.Json(setPushForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		setPushHandler)
	m.Get("/1/user/is_push_enabled",
		binding.Form(pushStatusForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		pushStatusHandler)
	m.Post("/1/user/enableAttention",
		binding.Json(relationshipForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		followHandler)
	m.Post("/1/user/enableDefriend",
		binding.Json(relationshipForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		loadUserHandler,
		checkLimitHandler,
		blacklistHandler)
	m.Get("/1/user/getAttentionFriendsList",
		binding.Form(getFollowsForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		getFollowsHandler)
	m.Get("/1/user/getAttentedMembersList",
		binding.Form(getFollowsForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		getFollowersHandler)
	m.Get("/1/user/getJoinedGroupsList",
		binding.Form(getFollowsForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		getGroupsHandler)
	m.Get("/1/user/getRelatedMembersList",
		binding.Form(socialListForm{}),
		ErrorHandler,
		socialListHandler)
}
示例#13
0
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)

}
示例#14
0
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()
}
示例#15
0
文件: sys.go 项目: shevilangle/sports
func BindSysApi(m *martini.ClassicMartini) {
	m.Get("/1/sys/config",
		binding.Form(getSysConfForm{}),
		ErrorHandler,
		checkTokenHandler,
		getSysConfHandler)
	m.Get("/m",
		mobileRedirectHandler)
}
示例#16
0
func BindFileApi(m *martini.ClassicMartini) {
	m.Post("/1/file/upload",
		binding.Form(fileUploadForm{}),
		//ErrorHandler,
		//checkTokenHandler,
		fileUploadHandler)
	m.Post("/1/file/delete",
		binding.Json(fileDeleteForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		fileDeleteHandler)
	m.Get("/1/file/uptoken",
		binding.Form(uptokenForm{}),
		ErrorHandler,
		checkTokenHandler,
		getQiniuTokenHandler)
	//m.Post("/1/file/upload", binding.MultipartForm(fileUploadForm2{}), ErrorHandler, fileUploadHandler2)
	//m.Get(ImageDownloadV1Uri, binding.Form(imageDownloadForm{}), ErrorHandler, imageDownloadHandler)
}
示例#17
0
func InitRoutes(m *martini.ClassicMartini) {
	m.Get("/", ListBlogs)
	m.Get("/new", NewBlog)
	m.Post("/new", binding.Form(models.Post{}), CreateBlog)
	m.Get("/post/:id", ShowBlog)

	m.NotFound(func(r render.Render) {
		fmt.Println("....................................................")
		r.HTML(404, "status/404", "")
	})
}
示例#18
0
//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}
}
示例#19
0
func configureRoutes(router martini.Router) {
	// 404 handler
	router.NotFound(func(render render.Render) {
		render.Redirect("/404")
	})

	// Common Routes
	router.Get("/", controllers.Home)
	router.Get("/404", controllers.NotFound)
	router.Get("/500", controllers.InternalServerError)

	// Player Routes
	router.Get("/players", controllers.GetPlayers)
	router.Get("/player/new", controllers.GetNewPlayer)
	router.Post("/player/new", binding.Form(controllers.PlayerData{}), controllers.CreatePlayer)
	router.Get("/player/:id", controllers.GetPlayerById)
	router.Post("/player/:id", binding.Form(controllers.PlayerData{}), binding.Form(controllers.OriginalData{}), controllers.ModifyPlayer)

	// Game Routes
	router.Get("/games", controllers.GetGames)
	router.Get("/game/new", controllers.GetNewGame)
	router.Post("/game/new", binding.Form(controllers.GameData{}), controllers.CreateGame)
	router.Get("/game/:id", controllers.GetGameById)
}
示例#20
0
func InitRoutes(m *martini.ClassicMartini) {

	m.Group("/devices", func(r martini.Router) {
		r.Get("", ListDevices)
		r.Post("", binding.Form(models.Device{}), CreateDevice)
		r.Get("/new", NewDevice)
		// r.Get("/:id", ShowDevice)
	})

	m.Get("/sock", Socket)
	m.Get("/node", Node)
	m.NotFound(func(r render.Render) {
		r.HTML(404, "status/404", "")
	})
}
示例#21
0
func main() {
	// Create martini
	m := martini.Classic()

	// Setup database connection
	db := setupDb(m)

	// Setup email configuration
	emailConfig := setupEmail(m)

	// Setup middleware
	m.Use(martini.Static("public"))
	m.Use(render.Renderer())
	m.Use(api.AuthenticateUser(db))

	// Create controllers
	pages := controllers.PagesController{}
	apiUsers := api.NewUsers(db, emailConfig)
	apiSchedules := api.NewSchedules(db)
	apiSyncs := api.NewSyncs(db)

	// Routing
	m.Get("/", pages.Home)

	m.Group("/api/users", func(r martini.Router) {
		r.Post("/login", apiUsers.Login)
		r.Post("/register", binding.Form(models.RegisterUser{}), apiUsers.Register)
		r.Post("/register_gcm", api.NeedsAuth(true), apiUsers.RegisterGcm)
		r.Post("/verify", api.NeedsAuth(false), apiUsers.Verify)
		r.Get("/search", api.NeedsAuth(true), apiUsers.Search)
	})

	m.Group("/api/schedules", func(r martini.Router) {
		r.Post("/add", api.NeedsAuth(true), apiSchedules.Add)
	})

	m.Group("/api/syncs", func(r martini.Router) {
		r.Get("/index", api.NeedsAuth(true), apiSyncs.Index)
		r.Post("/create", api.NeedsAuth(true), apiSyncs.Create)
	})

	// Start server
	m.Run()
}
示例#22
0
func main() {
	_, err := flags.ParseArgs(&opts, os.Args)
	PanicIf(err)

	m := martini.Classic()
	m.Map(SetupDB())

	// Serve static files from "static" directory.
	StaticOptions := martini.StaticOptions{Prefix: "static"}
	m.Use(martini.Static(opts.StaticDir, StaticOptions))

	// Render html templates from "templates" directory.
	m.Use(render.Renderer(render.Options{Directory: opts.TemplatesDir}))

	m.Get("/", IndexHandler)
	m.Post("/subscribe/", binding.Form(Subscription{}), SubscribeHandler)

	m.Run()
}
示例#23
0
func main() {
	m := martini.Classic()
	m.Use(render.Renderer())
	m.Use(DB())

	m.Get("/kv", func(r render.Render, db *kv.DB) {
		r.HTML(200, "list", AllDatas(db))
	})
	// binding.Form 将表单数据解析到 KVData结构体中,然后map到 request context中
	m.Post("/kv", binding.Form(KVData{}), func(data KVData, r render.Render, db *kv.DB) {
		err := db.Set([]byte(data.Key), []byte(data.Value))
		if err != nil {
			panic(err)
		}
		// fmt.Printf(">>>>>>> %s = %s \n", data.Key, data.Value)
		r.HTML(200, "list", AllDatas(db))
	})

	m.Run()
}
示例#24
0
func BindGroupApi(m *martini.ClassicMartini) {
	m.Post("/1/user/joinGroup",
		binding.Json(joinGroupForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		joinGroupHandler)
	m.Post("/1/user/newGroup",
		binding.Json(setGroupForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		setGroupHandler)
	m.Get("/1/user/getGroupInfo",
		binding.Form(groupInfoForm{}),
		ErrorHandler,
		groupInfoHandler)
	m.Get("/1/user/deleteGroup",
		binding.Json(groupDelForm{}, (*Parameter)(nil)),
		ErrorHandler,
		checkTokenHandler,
		delGroupHandler)
}
示例#25
0
文件: site.go 项目: vanzswc/blog
func main() {
	// BasicAuth credentials for admin functions
	username := "******"
	password := "******"

	m := martini.Classic()

	//needs import ("time")
	m.Use(render.Renderer(render.Options{
		Directory: "templates",
		Layout:    "layout",
		Funcs: []template.FuncMap{
			{
				"formatTime": func(args ...interface{}) string {
					t1 := time.Time(args[0].(time.Time))
					return t1.Format("Jan 2, 2006 at 3:04pm (MST)")
				},
				"unescaped": func(args ...interface{}) template.HTML {
					return template.HTML(args[0].(string))
				},
			},
		},
	}))

	// Middleware for mongodb connection
	m.Use(Mongo())

	// Setup static file serving
	m.Use(martini.Static("assets"))

	// Setup routing
	m.Get("/", BlogEntryList)
	m.Post("/blog/add/submit", auth.Basic(username, password), binding.Form(dbBlogEntry{}), addBlogEntrySubmit)
	m.Get("/blog/add", auth.Basic(username, password), addBlogEntry)
	m.Get("/post/:Id", BlogEntry)
	m.Get("/about", About)
	m.Get("/impressum", Impressum)

	m.Run()
}
示例#26
0
文件: main.go 项目: Gamec/gopasta
func main() {
	m := martini.Classic()
	m.Use(render.Renderer(render.Options{
		Directory: "templates",
		Layout:    "layout",
	}))

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

	m.Post("/new", binding.Form(Pasta{}), func(pasta Pasta, r render.Render) {
		pasta.UID = uniuri.New()
		pasta.CreatedAt = time.Now()

		DB.C("pastas").Insert(pasta)

		r.Redirect(pasta.UID)
	})

	m.Get("/:uid", func(r render.Render, params martini.Params) {
		pasta, err := PastaGet(params["uid"])

		fmt.Println(pasta)
		fmt.Println(err)

		if err != nil {
			r.HTML(http.StatusNotFound, "404", nil)
			return
		}

		r.HTML(http.StatusOK, "view", pasta)
	})

	m.Run()
}
示例#27
0
func main() {
	fmt.Print("Start")
	// init martini-framework
	mObj := martini.Classic()
	/* Add middleware (auth in this case, similiar to adding it
	to the Get method
	.Get( "/greetings/:name", Auth (<--- here),
			func(params martini.Params) string {
	*/
	//mObj.Use(Auth)
	mObj.Use(render.Renderer())
	mObj.Use(DB())

	mObj.Get("/test/",
		func() string {
			return "Test lübbt"
		})

	mObj.Get("/infos",
		func(r render.Render, db *mgo.Database) {
			//r.HTML(200, "/home/sascha//workspace/firsttest/src/github.com/sheisig0707/templates/test.tpl", GetAll(db))
			r.HTML(200, "infos", GetAll(db))
		})

	mObj.Get("/htmlmsg",
		func(r render.Render, db *mgo.Database) {
			//r.HTML(200, "/home/sascha//workspace/firsttest/src/github.com/sheisig0707/templates/test.tpl", GetAll(db))
			r.HTML(200, "test", GetAll(db))
		})

	mObj.Post("/htmlmsg", binding.Form(Msg{}),
		func(msg Msg, r render.Render, db *mgo.Database) {
			db.C("messages").Insert(msg)
			r.HTML(200, "test", GetAll(db))
		})

	mObj.Get("/api/addmsg/:user/:msg",
		func(params martini.Params, r render.Render, db *mgo.Database) {
			fmt.Print("User ist: " + params["user"])
			msg := Msg{Name: params["user"], Description: params["msg"]}

			//msg.Name = params["user"]
			//msg.Name = params["msg"]
			db.C("messages").Insert(msg)
			//r.HTML(200, "test", GetAll(db))
			r.HTML(200, "userMessagesAdded", GetByUser(db, params["user"]))
		})

	mObj.Get("/api/getAllmsg/:format",
		func(params martini.Params, r render.Render, db *mgo.Database) {
			if params["format"] == "json" {
				r.JSON(200, GetAll(db))
			} else {
				r.HTML(200, "allMessages", GetAll(db))
			}
		})

	mObj.Get("/api/getUsermsg/:user/:format",
		func(params martini.Params, r render.Render, db *mgo.Database) {
			//r.HTML(200, "/home/sascha//workspace/firsttest/src/github.com/sheisig0707/templates/test.tpl", GetAll(db))
			if params["format"] == "json" {
				r.JSON(200, GetAll(db))
			} else {
				r.HTML(200, "userMessages", GetByUser(db, params["user"]))
			}
		})

	mObj.Run()

}
示例#28
0
func BindConfigApi(m *martini.ClassicMartini) {
	m.Get("/admin/config/get", binding.Form(getConfigForm{}), getConfigHandler)
	m.Post("/admin/config/set", binding.Json(setConfigForm{}), setConfigHandler)
	m.Options("/admin/config/set", optionsHandler)
}
示例#29
0
文件: main.go 项目: freeformz/vertigo
// NewServer spaws a new Vertigo server
func NewServer() *martini.ClassicMartini {

	helpers := template.FuncMap{
		// unescape unescapes HTML of s.
		// Used in templates such as "/post/display.tmpl"
		"unescape": func(s string) template.HTML {
			return template.HTML(s)
		},
		// title renders post's Title as the HTML document's title.
		"title": func(t interface{}) string {
			post, exists := t.(Post)
			if exists {
				return post.Title
			}
			return Settings.Name
		},
		// description renders page description.
		// If none is defined, returns "Blog in Go" instead.
		"description": func() string {
			if Settings.Description == "" {
				return "Blog in Go"
			}
			return Settings.Description
		},
		// updated checks if post has been updated.
		"updated": func(p Post) bool {
			if p.Updated > p.Created {
				return true
			}
			return false
		},
		// date calculates unix date from d and offset in format: Monday, January 2, 2006 3:04PM (-0700 GMT)
		"date": func(d int64, offset int) string {
			return time.Unix(d, 0).UTC().In(time.FixedZone("", offset)).Format("Monday, January 2, 2006 3:04PM (-0700 GMT)")
		},
		// env returns environment variable of s.
		"env": func(s string) string {
			return os.Getenv(s)
		},
		// timezones returns all 416 valid IANA timezone locations.
		"timezones": func() [416]timezone.Timezone {
			return timezone.Locations
		},
	}

	m := martini.Classic()
	store := sessions.NewCookieStore([]byte(Settings.CookieHash))
	m.Use(sessions.Sessions("user", store))
	m.Use(Sessionchecker())
	m.Use(strict.Strict)
	m.Use(martini.Static("public", martini.StaticOptions{
		SkipLogging: true,
		// Adds 7 day Expire header for static files.
		Expires: func() string {
			return time.Now().Add(time.Hour * 168).UTC().Format("Mon, Jan 2 2006 15:04:05 GMT")
		},
	}))
	m.Use(render.Renderer(render.Options{
		Layout: "layout",
		Funcs:  []template.FuncMap{helpers}, // Specify helper function maps for templates to access.
	}))

	m.Get("/", Homepage)

	m.Get("/rss", ReadFeed)

	m.Group("/post", func(r martini.Router) {

		// Please note that `/new` route has to be before the `/:slug` route. Otherwise the program will try
		// to fetch for Post named "new".
		// For now I'll keep it this way to streamline route naming.
		r.Get("/new", ProtectedPage, func(res render.Render) {
			res.HTML(200, "post/new", nil)
		})
		r.Get("/:slug", ReadPost)
		r.Get("/:slug/edit", ProtectedPage, EditPost)
		r.Post("/:slug/edit", ProtectedPage, strict.ContentType("application/x-www-form-urlencoded"), binding.Form(Post{}), binding.ErrorHandler, UpdatePost)
		r.Get("/:slug/delete", ProtectedPage, DeletePost)
		r.Get("/:slug/publish", ProtectedPage, PublishPost)
		r.Get("/:slug/unpublish", ProtectedPage, UnpublishPost)
		r.Post("/new", ProtectedPage, strict.ContentType("application/x-www-form-urlencoded"), binding.Form(Post{}), binding.ErrorHandler, CreatePost)
		r.Post("/search", strict.ContentType("application/x-www-form-urlencoded"), binding.Form(Search{}), binding.ErrorHandler, SearchPost)

	})

	m.Group("/user", func(r martini.Router) {

		r.Get("", ProtectedPage, ReadUser)
		//r.Post("/delete", strict.ContentType("application/x-www-form-urlencoded"), ProtectedPage, binding.Form(User{}), DeleteUser)

		r.Get("/settings", ProtectedPage, ReadSettings)
		r.Post("/settings", strict.ContentType("application/x-www-form-urlencoded"), binding.Form(Vertigo{}), binding.ErrorHandler, ProtectedPage, UpdateSettings)

		r.Post("/installation", strict.ContentType("application/x-www-form-urlencoded"), binding.Form(Vertigo{}), binding.ErrorHandler, UpdateSettings)

		r.Get("/register", SessionRedirect, func(res render.Render) {
			res.HTML(200, "user/register", nil)
		})
		r.Post("/register", strict.ContentType("application/x-www-form-urlencoded"), binding.Form(User{}), binding.ErrorHandler, CreateUser)

		r.Get("/recover", SessionRedirect, func(res render.Render) {
			res.HTML(200, "user/recover", nil)
		})
		r.Post("/recover", strict.ContentType("application/x-www-form-urlencoded"), binding.Form(User{}), RecoverUser)
		r.Get("/reset/:id/:recovery", SessionRedirect, func(res render.Render) {
			res.HTML(200, "user/reset", nil)
		})
		r.Post("/reset/:id/:recovery", strict.ContentType("application/x-www-form-urlencoded"), binding.Form(User{}), ResetUserPassword)

		r.Get("/login", SessionRedirect, func(res render.Render) {
			res.HTML(200, "user/login", nil)
		})
		r.Post("/login", strict.ContentType("application/x-www-form-urlencoded"), binding.Form(User{}), LoginUser)
		r.Get("/logout", LogoutUser)

	})

	m.Group("/api", func(r martini.Router) {

		r.Get("", func(res render.Render) {
			res.HTML(200, "api/index", nil)
		})
		r.Get("/settings", ProtectedPage, ReadSettings)
		r.Post("/settings", strict.ContentType("application/json"), binding.Json(Vertigo{}), binding.ErrorHandler, ProtectedPage, UpdateSettings)
		r.Post("/installation", strict.ContentType("application/json"), binding.Json(Vertigo{}), binding.ErrorHandler, UpdateSettings)
		r.Get("/users", ReadUsers)
		r.Get("/user/logout", LogoutUser)
		r.Get("/user/:id", ReadUser)
		//r.Delete("/user", DeleteUser)
		r.Post("/user", strict.ContentType("application/json"), binding.Json(User{}), binding.ErrorHandler, CreateUser)
		r.Post("/user/login", strict.ContentType("application/json"), binding.Json(User{}), binding.ErrorHandler, LoginUser)
		r.Post("/user/recover", strict.ContentType("application/json"), binding.Json(User{}), RecoverUser)
		r.Post("/user/reset/:id/:recovery", strict.ContentType("application/json"), binding.Json(User{}), ResetUserPassword)

		r.Get("/posts", ReadPosts)
		r.Get("/post/:slug", ReadPost)
		r.Post("/post", strict.ContentType("application/json"), binding.Json(Post{}), binding.ErrorHandler, ProtectedPage, CreatePost)
		r.Get("/post/:slug/publish", ProtectedPage, PublishPost)
		r.Get("/post/:slug/unpublish", ProtectedPage, UnpublishPost)
		r.Post("/post/:slug/edit", strict.ContentType("application/json"), binding.Json(Post{}), binding.ErrorHandler, ProtectedPage, UpdatePost)
		r.Get("/post/:slug/delete", ProtectedPage, DeletePost)
		r.Post("/post", strict.ContentType("application/json"), binding.Json(Post{}), binding.ErrorHandler, ProtectedPage, CreatePost)
		r.Post("/post/search", strict.ContentType("application/json"), binding.Json(Search{}), binding.ErrorHandler, SearchPost)

	})

	m.Router.NotFound(strict.MethodNotAllowed, func(res render.Render) {
		res.HTML(404, "404", nil)
	})

	return m
}
示例#30
0
func BindStatApi(m *martini.ClassicMartini) {
	m.Get("/admin/stat/summary", binding.Form(summaryForm{}), adminErrorHandler, summaryHandler)
	m.Get("/admin/stat/retention", binding.Form(retentionForm{}), adminErrorHandler, retentionHandler)
}