Beispiel #1
6
func prepareRoutes(router *gin.Engine) {
	// Web Resources
	router.Static("/static", "web/dist")

	// API Routes
	api := router.Group("/api/v1")
	admin := api.Group("/admin")
	public := api.Group("/public")
	registered := api.Group("/")
	sameRegisteredUser := api.Group("/user")

	prepareMiddleware(admin, public, registered, sameRegisteredUser)

	admin.GET("/users", listUsers)
	admin.GET("/places", listPlaces)
	admin.POST("/places", createPlace)
	admin.POST("/events", createEvent)
	admin.PUT("/place/:placeId", updatePlace)
	admin.PUT("/event/:eventId", updateEvent)
	admin.DELETE("/event/:eventId", cancelEvent)

	sameRegisteredUser.GET("/:userId", getUser)
	sameRegisteredUser.PUT("/:userId", updateUser)
	sameRegisteredUser.DELETE("/:userId", disableUser)

	registered.POST("/buy/:seatId", buyTicket)

	public.GET("/place/:placeId", getPlace)
	public.GET("/events", listEvents)
	public.GET("/event/:eventId", getEvent)
	public.POST("/users", createUser) // TODO Checar, me huele raro......
	public.POST("/login", loginUser)
}
Beispiel #2
1
// InitAssetsTemplates initializes the router to use either a ricebox or the
// filesystem in case the ricebox couldn't be found.
func InitAssetsTemplates(r *gin.Engine, tbox, abox *rice.Box, verbose bool, names ...string) error {
	var err error

	if tbox != nil {
		mt := multitemplate.New()
		var tmpl string
		var message *template.Template
		for _, x := range names {
			if tmpl, err = tbox.String(x); err != nil {
				return err
			}
			if message, err = template.New(x).Parse(tmpl); err != nil {
				return err
			}
			mt.Add(x, message)
		}
		logger.Debug("server", "Loaded templates from \"templates\" box")
		r.HTMLRender = mt
	} else {
		r.LoadHTMLGlob("templates/*")
		logger.Debug("server", "Loaded templates from disk")
	}

	if abox != nil {
		r.StaticFS("/static", abox.HTTPBox())
		logger.Debug("server", "Loaded assets from \"assets\" box")
	} else {
		r.Static("/static", "assets")
		logger.Debug("server", "Loaded assets from disk")
	}
	return nil
}
Beispiel #3
0
func InitRooter(e *gin.Engine) {
	e.GET("/status", func(c *gin.Context) { c.String(http.StatusOK, "ok") })

	e.GET("/searchUser", userService.ListEndpoint)
	e.GET("/searchItem", itemService.ListEndpoint)
	e.GET("/searchPost", postService.ListEndpoint)

	e.GET("/user/:id", userService.GetWebEndpoint)
	e.GET("/item/:id", itemService.GetWebEndpoint)
	e.GET("/post/:id", postService.GetWebEndpoint)

	e.Static("/static", "./static")
	//
	//	json := e.Group("/json")
	//	{
	//		json.GET("user/detail/:id", auth(), userService.GetEndpoint)
	//		json.GET("user/list", auth(), userService.ListEndpoint)
	//	}
	//
	//	web := e.Group("/web")
	//	{
	//		web.GET("user/detail/:id", auth(), userService.GetWebEndpoint)
	//		web.GET("user/list", auth(), userService.ListWebEndpoint)
	//	}
	//
	//	// However, this one will match /user/john/ and also /user/john/send
	//	// If no other routers match /user/john, it will redirect to /user/join/
	//	e.GET("/user/:name/*action", func(c *gin.Context) {
	//		name := c.Param("name")
	//		action := c.Param("action")
	//		message := name + " is " + action
	//		c.String(http.StatusOK, message)
	//	})

}
Beispiel #4
0
func registerRoutes(e *gin.Engine) {
	controller := rc.ResourceController{}
	controller.DatabaseProvider = Database

	resourceNames := []string{"RecordMatchContext",
		"RecordMatchSystemInterface", "RecordSet"}

	for _, name := range resourceNames {
		e.GET("/"+name+"/:id", controller.GetResource)
		e.POST("/"+name, controller.CreateResource)
		e.PUT("/"+name+"/:id", controller.UpdateResource)
		e.DELETE("/"+name+"/:id", controller.DeleteResource)
		e.GET("/"+name, controller.GetResources)
	}

	e.POST("/AnswerKey", controller.SetAnswerKey)

	name := "RecordMatchRun"
	e.GET("/"+name, controller.GetResources)
	e.GET("/"+name+"/:id", controller.GetResource)
	e.POST("/"+name, rc.CreateRecordMatchRunHandler(Database))
	e.PUT("/"+name+"/:id", controller.UpdateResource)
	e.DELETE("/"+name+"/:id", controller.DeleteResource)

	e.GET("/RecordMatchRunMetrics", rc.GetRecordMatchRunMetricsHandler(Database))
	e.GET("/RecordMatchRunLinks/:id", rc.GetRecordMatchRunLinksHandler(Database))

	e.Static("/ptmatch/api/", "api")
}
Beispiel #5
0
// setupRoutes is an internal method where we setup application routes
func setupRoutes(r *gin.Engine) {
	// TODO: home route "/" is not yet defined.
	// r.GET("/", ...)

	// static files served by application
	r.Static("/static", "./static")

	// auth urls for the login form and logout url
	r.GET("/login", auth.Login)
	r.POST("/login", auth.Login)
	r.GET("/logout", auth.Logout)

	// sessionResource is a special auth api resource, with POST and DELETE
	// endpoints used for logging a user in or out.
	sessionResource := r.Group("/api/session")
	{
		sessionResource.POST("", auth.LoginAPI)
		sessionResource.DELETE("", auth.LogoutAPI)
	}

	// admin urls
	adminRoutes := r.Group("/admin", auth.LoginRequired())
	{
		adminRoutes.GET("", admin.Admin)
		adminRoutes.GET("/json", admin.JSONTest)
	}
}
Beispiel #6
0
func SetStaticRoutes(router *gin.Engine) *gin.Engine {

	router.LoadHTMLFiles("views/index.html")
	router.Static("/static", "./static")

	router.GET("/", func(c *gin.Context) {
		c.HTML(http.StatusOK, "index.html", gin.H{})
	})

	router.GET("/ping", func(c *gin.Context) {
		c.String(200, "pong")
	})

	return router
}
Beispiel #7
0
func LoadPage(parentRoute *gin.Engine) {
	//type Page struct {
	//    Title string
	//}

	parentRoute.SetHTMLTemplate(template.Must(template.ParseFiles("frontend/canjs/templates/message.html", "frontend/canjs/templates/app.html", "frontend/canjs/templates/base.html", "frontend/canjs/templates/404.html")))
	log.Debug("url : " + config.StaticUrl)
	log.Debug("guid : " + config.Guid)
	log.Debug("path : " + staticPath)
	parentRoute.Static(config.StaticUrl+"/"+config.Guid, staticPath)
	// route.ServeFiles doesn't exist in the current version of gin. If you want to use this, use the 59d949d35080b83864dbeafadecef112d46aaeee.
	//parentRoute.ServeFiles(config.StaticUrl+"/"+config.Guid+"/*filepath", http.Dir(staticPath))
	parentRoute.NoRoute(func(c *gin.Context) {
		c.HTML(404, "404.html", map[string]string{"language": config.DefaultLanguage, "title": config.Title})
	})

	route.Route(parentRoute.Group(""))
}
Beispiel #8
0
func RegisterRoute(r *gin.Engine) {
	loadHTMLGlob(r, path.Join(config.GLOBAL_CONFIG.TemplatePath, "*"), registerDefaultFunctions)

	r.GET("/", IndexAction)
	r.GET("/post/:postId", ShowPostAction)

	r.POST("/login", LoginAction)
	r.POST("/register", RegisterAction)
	r.GET("/logout", LogoutAction)

	r.GET("/new_post", ShowNewPostPageAction)
	r.POST("/posts", NewPostAction)

	// admin
	r.GET("/admin/users", controllers.ShowUsersAction)

	r.Static("/statics", config.GLOBAL_CONFIG.StaticPath)

	r.NoRoute(NoRouteHandler)
}
Beispiel #9
0
func setupStatic(router *gin.Engine) {
	router.Static("/css", STATIC_DIR+"css")
	router.Static("/js", STATIC_DIR+"js")
	router.LoadHTMLGlob(STATIC_DIR + "tpl/*.tpl")
}
Beispiel #10
0
func ExposeRoutes(router *gin.Engine) {
	router.LoadHTMLGlob("web/templates/*.html")
	router.HTMLRender = createCustomRender()
	if config.IsEnvironment("production") && config.GetConfig("SPACE_CDN") != "" {
		spaceCDN = config.GetConfig("SPACE_CDN")
	} else {
		spaceCDN = "/public"
		router.Static("/public", "web/public")
	}
	store := sessions.NewCookieStore([]byte(config.GetConfig("SPACE_SESSION_SECRET")))
	store.Options(sessions.Options{
		Secure:   config.IsEnvironment("production"),
		HttpOnly: true,
	})
	router.Use(sessions.Sessions("jupiter.session", store))
	views := router.Group("/")
	{
		views.GET("/", jupiterHandler)
		views.GET("/profile", jupiterHandler)

		views.GET("/signup", func(c *gin.Context) {
			c.HTML(http.StatusOK, "satellite", utils.H{
				"AssetsEndpoint": spaceCDN,
				"Title":          " - Sign up",
				"Satellite":      "io",
				"Data": utils.H{
					"feature.gates": utils.H{
						"user.create": feature.Active("user.create"),
					},
				},
			})
		})

		views.GET("/signin", func(c *gin.Context) {
			c.HTML(http.StatusOK, "satellite", utils.H{
				"AssetsEndpoint": spaceCDN,
				"Title":          " - Sign in",
				"Satellite":      "ganymede",
			})
		})

		views.GET("/signout", func(c *gin.Context) {
			session := sessions.Default(c)

			userPublicId := session.Get("userPublicId")
			if userPublicId != nil {
				session.Delete("userPublicId")
				session.Save()
			}

			c.Redirect(http.StatusFound, "/signin")
		})

		views.GET("/session", func(c *gin.Context) {
			session := sessions.Default(c)

			userPublicId := session.Get("userPublicId")
			if userPublicId != nil {
				c.Redirect(http.StatusFound, "/")
				return
			}

			var nextPath string = "/"
			var scope string = c.Query("scope")
			var grantType string = c.Query("grant_type")
			var code string = c.Query("code")
			var clientId string = c.Query("client_id")
			var _nextPath string = c.Query("_")
			//var state string = c.Query("state")

			if scope == "" || grantType == "" || code == "" || clientId == "" {
				// Original response:
				// c.String(http.StatusMethodNotAllowed, "Missing required parameters")
				c.Redirect(http.StatusFound, "/signin")
				return
			}
			if _nextPath != "" {
				if _nextPath, err := url.QueryUnescape(_nextPath); err == nil {
					nextPath = _nextPath
				}
			}

			client := services.FindOrCreateClient("Jupiter")
			if client.Key == clientId && grantType == oauth.AuthorizationCode && scope == models.PublicScope {
				grantToken := services.FindSessionByToken(code, models.GrantToken)
				if grantToken.ID != 0 {
					session.Set("userPublicId", grantToken.User.PublicId)
					session.Save()
					services.InvalidateSession(grantToken)
					c.Redirect(http.StatusFound, nextPath)
					return
				}
			}

			c.Redirect(http.StatusFound, "/signin")
		})

		views.GET("/authorize", authorizeHandler)
		views.POST("/authorize", authorizeHandler)

		views.GET("/error", func(c *gin.Context) {
			errorReason := c.Query("response_type")

			c.HTML(http.StatusOK, "error", utils.H{
				"AssetsEndpoint": spaceCDN,
				"errorReason":    errorReason,
			})
		})

		views.POST("/token", func(c *gin.Context) {
			var grantType string = c.PostForm("grant_type")

			authorizationBasic := strings.Replace(c.Request.Header.Get("Authorization"), "Basic ", "", 1)
			client := oauth.ClientAuthentication(authorizationBasic)
			if client.ID == 0 {
				c.Header("WWW-Authenticate", fmt.Sprintf("Basic realm=\"%s\"", c.Request.RequestURI))
				c.JSON(http.StatusUnauthorized, utils.H{
					"error": oauth.AccessDenied,
				})
				return
			}

			switch grantType {
			// Authorization Code Grant
			case oauth.AuthorizationCode:
				result, err := oauth.AccessTokenRequest(utils.H{
					"grant_type":   grantType,
					"code":         c.PostForm("code"),
					"redirect_uri": c.PostForm("redirect_uri"),
					"client":       client,
				})
				if err != nil {
					c.JSON(http.StatusMethodNotAllowed, utils.H{
						"error": result["error"],
					})
					return
				} else {
					c.JSON(http.StatusOK, utils.H{
						"user_id":       result["user_id"],
						"access_token":  result["access_token"],
						"token_type":    result["token_type"],
						"expires_in":    result["expires_in"],
						"refresh_token": result["refresh_token"],
						"scope":         result["scope"],
					})
					return
				}
				return
			// Refreshing an Access Token
			case oauth.RefreshToken:
				result, err := oauth.RefreshTokenRequest(utils.H{
					"grant_type":    grantType,
					"refresh_token": c.PostForm("refresh_token"),
					"scope":         c.PostForm("scope"),
					"client":        client,
				})
				if err != nil {
					c.JSON(http.StatusMethodNotAllowed, utils.H{
						"error": result["error"],
					})
					return
				} else {
					c.JSON(http.StatusOK, utils.H{
						"user_id":       result["user_id"],
						"access_token":  result["access_token"],
						"token_type":    result["token_type"],
						"expires_in":    result["expires_in"],
						"refresh_token": result["refresh_token"],
						"scope":         result["scope"],
					})
					return
				}
				return
			// Resource Owner Password Credentials Grant
			// Client Credentials Grant
			case oauth.Password, oauth.ClientCredentials:
				c.JSON(http.StatusMethodNotAllowed, utils.H{
					"error": oauth.UnsupportedGrantType,
				})
				return
			default:
				c.JSON(http.StatusBadRequest, utils.H{
					"error": oauth.InvalidRequest,
				})
				return
			}
		})
	}
}
Beispiel #11
0
func route(r *gin.Engine) {
	r.Static("/assets", "assets")
	r.GET("/", getApp)
	r.GET("/search", getSearch)
	r.POST("/result", postResult)
}
Beispiel #12
0
//	注册路由
func RegisterRoute(route *gin.Engine) {

	//	静态文件目录
	route.Static("static", "./static")

	//	注册模板
	registerTemplates("static/html/layout.html", "static/html/twocolorball/index.html")
	registerTemplates("static/html/layout.html", "static/html/twocolorball/analyze1.html")
	registerTemplates("static/html/layout.html", "static/html/twocolorball/analyze2.html")
	registerTemplates("static/html/layout.html", "static/html/superlotto/index.html")
	registerTemplates("static/html/layout.html", "static/html/superlotto/analyze1.html")
	registerTemplates("static/html/layout.html", "static/html/superlotto/analyze2.html")

	//	首页默认转到双色球列表
	route.GET("/", func(c *gin.Context) {
		c.Redirect(http.StatusMovedPermanently, "/twocolorball")
	})

	//	双色球
	t := route.Group("/twocolorball")
	{
		//	列表页面
		t.GET("/", func(c *gin.Context) {
			err := processTemplate(c.Writer, "static/html/twocolorball/index.html", nil)
			if err != nil {
				log.Print(err)
			}
		})

		//	列表查询
		t.GET("/list", func(c *gin.Context) {

			paramN := c.Query("n")
			n, err := strconv.Atoi(paramN)
			if err != nil {
				c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("错误的查询参数N:%s", paramN)))
				return
			}

			//  查询
			results, err := twocolorball.Query(n)
			if err != nil {
				c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("查询双色球数据失败:%v", err)))
				return
			}

			c.JSON(http.StatusOK, entity.ResultD(results))
		})

		//	分析1页面
		t.GET("/analyze1", func(c *gin.Context) {
			err := processTemplate(c.Writer, "static/html/twocolorball/analyze1.html", nil)
			if err != nil {
				log.Print(err)
			}
		})

		//	分析1查询
		t.GET("/doanalyze1", func(c *gin.Context) {

			reds := c.Query("reds")
			blues := c.Query("blues")

			//  红球
			redNums := make([]int, 0)

			if len(reds) > 0 {
				parts := strings.Split(reds, ",")
				for _, value := range parts {
					i, err := strconv.Atoi(value)
					if err != nil {
						c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("输入的参数有误:%s", value)))
						return
					}

					redNums = append(redNums, i)
				}
			}

			//  蓝球
			blueNum, err := strconv.Atoi(blues)

			//  查询
			results, err := twocolorball.Analyze1(redNums, blueNum)
			if err != nil {
				c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("分析双色球数据失败:%v", err)))
				return
			}

			c.JSON(http.StatusOK, entity.ResultD(results))
		})

		//	分析2页面
		t.GET("/analyze2", func(c *gin.Context) {
			err := processTemplate(c.Writer, "static/html/twocolorball/analyze2.html", nil)
			if err != nil {
				log.Print(err)
			}
		})

		//	分析2查询
		t.GET("/doanalyze2", func(c *gin.Context) {

			reds := c.Query("reds")
			blues := c.Query("blues")

			//  红球
			redNums := make([]int, 0)

			if len(reds) > 0 {
				parts := strings.Split(reds, ",")
				for _, value := range parts {
					i, err := strconv.Atoi(value)
					if err != nil {
						c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("输入的参数有误:%s", value)))
						return
					}

					redNums = append(redNums, i)
				}
			}

			//  蓝球
			blueNum, err := strconv.Atoi(blues)

			//  查询
			results, err := twocolorball.Analyze2(redNums, blueNum)
			if err != nil {
				c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("分析双色球数据失败:%v", err)))
				return
			}

			c.JSON(http.StatusOK, entity.ResultD(results))
		})
	}

	//	大乐透
	s := route.Group("/superlotto")
	{
		//	列表页面
		s.GET("/", func(c *gin.Context) {
			err := processTemplate(c.Writer, "static/html/superlotto/index.html", nil)
			if err != nil {
				log.Print(err)
			}
		})

		//	列表查询
		s.GET("/list", func(c *gin.Context) {

			paramN := c.Query("n")
			n, err := strconv.Atoi(paramN)
			if err != nil {
				c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("错误的查询参数N:%s", paramN)))
				return
			}

			//  查询
			results, err := superlotto.Query(n)
			if err != nil {
				c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("查询大乐透数据失败:%v", err)))
				return
			}

			c.JSON(http.StatusOK, entity.ResultD(results))
		})

		//	分析1页面
		s.GET("/analyze1", func(c *gin.Context) {
			err := processTemplate(c.Writer, "static/html/superlotto/analyze1.html", nil)
			if err != nil {
				log.Print(err)
			}
		})

		//	分析1查询
		s.GET("/doanalyze1", func(c *gin.Context) {

			reds := c.Query("reds")
			blues := c.Query("blues")

			//  红球
			redNums := make([]int, 0)

			if len(reds) > 0 {
				parts := strings.Split(reds, ",")
				for _, value := range parts {
					i, err := strconv.Atoi(value)
					if err != nil {
						c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("输入的参数有误:%s", value)))
						return
					}

					redNums = append(redNums, i)
				}
			}

			//  蓝球
			blueNums := make([]int, 0)
			if len(blues) > 0 {
				parts := strings.Split(blues, ",")
				for _, value := range parts {
					i, err := strconv.Atoi(value)
					if err != nil {
						c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("输入的参数有误:%s", value)))
						return
					}

					blueNums = append(blueNums, i)
				}
			}

			//  查询
			results, err := superlotto.Analyze1(redNums, blueNums)
			if err != nil {
				c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("分析大乐透数据失败:%v", err)))
				return
			}

			c.JSON(http.StatusOK, entity.ResultD(results))
		})

		//	分析2页面
		s.GET("/analyze2", func(c *gin.Context) {
			err := processTemplate(c.Writer, "static/html/superlotto/analyze2.html", nil)
			if err != nil {
				log.Print(err)
			}
		})

		//	分析2查询
		s.GET("/doanalyze2", func(c *gin.Context) {

			reds := c.Query("reds")
			blues := c.Query("blues")

			//  红球
			redNums := make([]int, 0)

			if len(reds) > 0 {
				parts := strings.Split(reds, ",")
				for _, value := range parts {
					i, err := strconv.Atoi(value)
					if err != nil {
						c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("输入的参数有误:%s", value)))
						return
					}

					redNums = append(redNums, i)
				}
			}

			//  蓝球
			blueNums := make([]int, 0)
			if len(blues) > 0 {
				parts := strings.Split(blues, ",")
				for _, value := range parts {
					i, err := strconv.Atoi(value)
					if err != nil {
						c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("输入的参数有误:%s", value)))
						return
					}

					blueNums = append(blueNums, i)
				}
			}

			//  查询
			results, err := superlotto.Analyze2(redNums, blueNums)
			if err != nil {
				c.JSON(http.StatusOK, entity.ResultSM(false, fmt.Sprintf("分析大乐透数据失败:%v", err)))
				return
			}

			c.JSON(http.StatusOK, entity.ResultD(results))
		})
	}
}