func UserRouter(router *gin.RouterGroup, db gorm.DB) { router.GET("", func(ctx *gin.Context) { result := usermodel.Fetch(&db) fmt.Println(result) ctx.JSON(http.StatusOK, result.Value) }) router.GET("/:id", func(ctx *gin.Context) { userId := ctx.Param("id") user := usermodel.FetchUserById(userId, &db) ctx.JSON(http.StatusOK, user.Value) }) router.POST("", func(ctx *gin.Context) { user := usermodel.UserJSON{} ctx.BindJSON(&user) result := usermodel.Create(&user, &db) if result.Error != nil { ctx.JSON(http.StatusBadRequest, utils.HTTPError{Error: error(result.Error)}) } else { ctx.JSON(http.StatusOK, result.Value) } }) router.DELETE("/:id", func(ctx *gin.Context) { userId := ctx.Param("id") result := usermodel.Remove(userId, &db) if result.Error != nil { ctx.JSON(http.StatusBadRequest, utils.HTTPError{Error: error(result.Error)}) } else { ctx.JSON(http.StatusOK, nil) } }) router.PUT("/:id", func(ctx *gin.Context) { user := usermodel.UserJSON{} ctx.BindJSON(&user) result := usermodel.Update(ctx.Param("id"), &user, &db) if result.Error != nil { ctx.JSON(http.StatusBadRequest, utils.HTTPError{Error: error(result.Error)}) } else { ctx.JSON(http.StatusOK, result.Value) } }) }
func Person(router *gin.RouterGroup) { router.GET("/persons", handler.GetAll) router.GET("/person/:id", handler.GetById) router.POST("/person", handler.Create) router.PUT("/person", handler.Update) router.DELETE("/person", handler.Delete) }
func api(api *gin.RouterGroup) { api.POST("/point", func(c *gin.Context) { p := point.Point{} err := c.Bind(&p) hash, err := hash.NewHashPoint(p) if err != nil || !p.IsValid() { c.JSON(http.StatusBadRequest, "Invalid point") } else { c.JSON(http.StatusOK, gin.H{ "point": p, "hash": reverseString(hash.String), "zorder": reverseString(hash.GetZorder().HashString(32)), }) } }) api.POST("/hash", func(c *gin.Context) { hash := &hash.Hash{} err := c.Bind(&hash) hash.String = reverseString(hash.String) if err != nil || hash.InitFromString() != nil { c.JSON(http.StatusBadRequest, "Invalid hash") } else { c.JSON(http.StatusOK, gin.H{ "hash": reverseString(hash.String), "point": hash.GenPoint(), "zorder": reverseString(hash.GetZorder().HashString(32)), }) } }) }
// Listen Tells Gin API to start func Listen(iface string, s *discordgo.Session, logger *logging.Logger) { // set the refs to point to main var v1 *gin.RouterGroup session = s c := config.Get() log = logger if c.LogLevel != "debug" { gin.SetMode(gin.ReleaseMode) } //r := gin.Default() r := gin.New() r.Use(loggerino()) r.Use(gin.Recovery()) if c.APIPassword != "" { log.Info("Basic Authentication enabled for API") v1 = r.Group("/v1", gin.BasicAuth(gin.Accounts{ c.APIUsername: c.APIPassword, })) } else { log.Warning("DIGO_API_PASSWORD and DIGO_API_USERNAME are not set") log.Warning("The API is open to all requests") v1 = r.Group("/v1") } v1.GET("/version", versionV1) v1.GET("/channels", channelsV1) v1.POST("/message", messageV1) go r.Run(iface) log.Noticef("Digo API is listening on %s", c.APIInterface) }
// Use is a function func Use(r *gin.RouterGroup) { r.Use() { r.GET("/image/all", getAllImages) r.GET("/image/search", getSearchImages) r.POST("/image", createImage) } }
// Setup will setup all API routes. func Setup(group *gin.RouterGroup, db *db.DB) { group.Use() { group.GET("/items/:code", itemsShowHandler(db)) group.DELETE("/items/:code", itemsDestroyHandler(db)) group.GET("/items", itemsIndexHandler(db)) group.POST("/items", itemsCreateHandler(db)) } }
// Use is an exported function that // define routing for user func Use(r *gin.RouterGroup) { r.Use() { r.GET("/user", getUsers) r.GET("/user/:id", getUser) r.POST("/user", postUser) r.PATCH("/user/:id", updateUser) r.DELETE("/user/:id", deleteUser) } }
func NewBuildController(s *gin.RouterGroup) *BuildController { ctl := &BuildController{} s.POST("/apps/:id/builds", ctl.postBuild) s.GET("/apps/:id/builds", ctl.getBuildList) s.POST("/apps/:id/builds/:build_id/deploy", ctl.postBuildDeploy) return ctl }
func NewConfigController(s *gin.RouterGroup) *ConfigController { ctl := &ConfigController{} s.POST("/apps/:id/configs", ctl.postConfig) s.PUT("/apps/:id/configs/:config_id", ctl.putConfig) s.GET("/apps/:id/configs", ctl.getConfigList) s.GET("/apps/:id/configs/:config_id", ctl.getConfig) return ctl }
func NewNodeController(s *gin.RouterGroup) *NodeController { ctl := &NodeController{} s.GET("/nodes/register.sh", ctl.getRegisterSH) s.POST("/nodes", ctl.postNode) s.GET("/nodes", ctl.getAllNode) s.GET("/nodes/config/:filename", ctl.getNodeConfig) return ctl }
func (mm *ModuleManager) RegisterRouterGroup(group *gin.RouterGroup) { group.GET("/", func(c *gin.Context) { c.JSON(http.StatusOK, (*mm).GetAllModules()) }) group.POST("/", func(c *gin.Context) { var req shared.Module err := c.BindJSON(&req) if err != nil { c.JSON(400, shared.HttpError{"Decoding HTTP body failed.", err}) return } if strings.TrimSpace(req.ModuleURL) == "" { c.JSON(400, shared.HttpError{"Attribute 'module-url' is missing.", nil}) return } if mm.GetModule(req.Metadata.ID) != nil { c.JSON(423, shared.HttpError{"Module already registered.", nil}) return } mm.AddModule(&req) }) group.Any("/:module/proxy/*path", func(c *gin.Context) { module := mm.GetModule(c.Param("module")) if module == nil { c.JSON(404, shared.HttpError{"Module not found.", nil}) return } target, err := url.Parse(module.ModuleURL) if module == nil { c.JSON(500, shared.HttpError{"Error connecting to module.", err}) return } oldPrefix := fmt.Sprintf("%s/%s/proxy", group.BasePath(), module.Metadata.ID) newPrefix := "/module" var handler http.Handler handler = httputil.NewSingleHostReverseProxy(target) handler = HTTPAddPrefix(newPrefix, handler) handler = http.StripPrefix(oldPrefix, handler) wrapper := gin.WrapH(handler) wrapper(c) }) }
// It defines // POST: /path // GET: /path // PUT: /path/:id // POST: /path/:id func CRUD(group *gin.RouterGroup, path string, resource interface{}) { if resource, ok := resource.(CreateSupported); ok { group.POST(path, resource.CreateHandler) } if resource, ok := resource.(ListSupported); ok { group.GET(path, resource.ListHandler) } if resource, ok := resource.(TakeSupported); ok { group.GET(path+"/:id", resource.TakeHandler) } if resource, ok := resource.(UpdateSupported); ok { group.PUT(path+"/:id", resource.UpdateHandler) } if resource, ok := resource.(DeleteSupported); ok { group.DELETE(path+"/:id", resource.DeleteHandler) } }
// initRoutesUsers initialized routes for Users Controller func initRoutesUsers(router *gin.RouterGroup, checkPassword gin.HandlerFunc) { usersCtrl := &UsersController{} gs := router.Group("/users") gs.Use(checkPassword) { gs.GET("", usersCtrl.List) } g := router.Group("/user") g.Use(checkPassword) { g.GET("/me", usersCtrl.Me) g.GET("/me/contacts/:sinceSeconds", usersCtrl.Contacts) g.POST("/me/contacts/:username", usersCtrl.AddContact) g.DELETE("/me/contacts/:username", usersCtrl.RemoveContact) g.POST("/me/topics/*topic", usersCtrl.AddFavoriteTopic) g.DELETE("/me/topics/*topic", usersCtrl.RemoveFavoriteTopic) g.POST("/me/tags/:tag", usersCtrl.AddFavoriteTag) g.DELETE("/me/tags/:tag", usersCtrl.RemoveFavoriteTag) g.POST("/me/enable/notifications/topics/*topic", usersCtrl.EnableNotificationsTopic) g.POST("/me/disable/notifications/topics/*topic", usersCtrl.DisableNotificationsTopic) g.POST("/me/enable/notifications/alltopics", usersCtrl.EnableNotificationsAllTopics) g.POST("/me/disable/notifications/alltopics", usersCtrl.DisableNotificationsAllTopics) } admin := router.Group("/user") admin.Use(checkPassword, CheckAdmin()) { admin.PUT("/convert", usersCtrl.Convert) admin.PUT("/archive", usersCtrl.Archive) admin.PUT("/rename", usersCtrl.Rename) admin.PUT("/update", usersCtrl.Update) admin.PUT("/setadmin", usersCtrl.SetAdmin) admin.PUT("/resetsystem", usersCtrl.ResetSystemUser) admin.PUT("/updatesystem", usersCtrl.UpdateSystemUser) admin.PUT("/check", usersCtrl.Check) } router.GET("/user/verify/:username/:tokenVerify", usersCtrl.Verify) router.POST("/user/reset", usersCtrl.Reset) router.POST("/user", usersCtrl.Create) }
// ConfigureRoutes configures the routes for this controller func (dc *DataController) ConfigureRoutes(route *gin.RouterGroup) { route.POST("saveServer", dc.saveServer) route.POST("deleteServer", dc.deleteServer) route.GET("loadServers", dc.loadServers) route.GET("loadSettings", dc.loadSettings) route.POST("saveSettings", dc.saveSettings) route.GET("findPackets", dc.findPackets) route.GET("countPackets", dc.countPackets) route.GET("loadLogFile", dc.loadLogFile) route.GET("clearLogFile", dc.clearLogFile) }
// ConfigureRoutes configures the routes for this controller func (dc *DownloadsController) ConfigureRoutes(route *gin.RouterGroup) { route.POST("downloadPacket", dc.downloadPacket) route.POST("startDirectDownload", dc.startDirectDownload) route.GET("listDownloads", dc.listDownloads) route.POST("stopDownload", dc.stopDownload) route.POST("cancelDownload", dc.cancelDownload) route.POST("resumeDownload", dc.resumeDownload) route.GET("loadFiles", dc.loadFiles) route.POST("deleteFiles", dc.deleteFiles) route.POST("moveFilesToMovies", dc.moveFilesToMovies) }
func (svc *Service) Run(cfg ServerSettings) error { config = cfg // save config in global // init gin if !config.Configuration.DebugEnabled { gin.SetMode(gin.ReleaseMode) } var oauth2Endpoint = oauth2.Endpoint{ AuthURL: config.Configuration.AuthURL, TokenURL: config.Configuration.TokenURL, } // Middleware router := gin.New() // use glog for logging router.Use(ginglog.Logger(config.Configuration.LogFlushInterval)) // monitoring GO internals and counter middleware counterAspect := &ginmon.CounterAspect{0} asps := []aspects.Aspect{counterAspect} router.Use(ginmon.CounterHandler(counterAspect)) router.Use(gomonitor.Metrics(9000, asps)) router.Use(ginoauth2.RequestLogger([]string{"uid", "team"}, "data")) // last middleware router.Use(gin.Recovery()) // OAuth2 secured if conf.Oauth2Enabled is set var private *gin.RouterGroup //ATM team or user auth is mutually exclusive, we have to look for a better solution if config.Configuration.Oauth2Enabled { private = router.Group("") if config.Configuration.TeamAuthorization { var accessTuple []zalando.AccessTuple = make([]zalando.AccessTuple, len(config.Configuration.AuthorizedTeams)) for i, v := range config.Configuration.AuthorizedTeams { accessTuple[i] = zalando.AccessTuple{Realm: v.Realm, Uid: v.Uid, Cn: v.Cn} } zalando.AccessTuples = accessTuple private.Use(ginoauth2.Auth(zalando.GroupCheck, oauth2Endpoint)) } else { var accessTuple []zalando.AccessTuple = make([]zalando.AccessTuple, len(config.Configuration.AuthorizedUsers)) for i, v := range config.Configuration.AuthorizedUsers { accessTuple[i] = zalando.AccessTuple{Realm: v.Realm, Uid: v.Uid, Cn: v.Cn} } private.Use(ginoauth2.Auth(zalando.UidCheck, oauth2Endpoint)) } } //non authenticated routes router.GET("/", rootHandler) router.GET("/health", healthHandler) //authenticated routes if config.Configuration.Oauth2Enabled { private.GET("/deployments", deployList) private.GET("/deployments/:name", deployInfo) private.POST("/deployments", deployCreate) private.PUT("/deployments/:name", deployUpsert) private.DELETE("/deployments/:name", deployDelete) private.PATCH("/deployments/:name/replicas/:num", deployReplicasModify) } else { router.GET("/deployments", deployList) router.GET("/deployments/:name", deployInfo) router.POST("/deployments", deployCreate) router.PUT("/deployments/:name", deployUpsert) router.DELETE("/deployments/:name", deployDelete) router.PATCH("/deployments/:name/replicas/:num", deployReplicasModify) } // TLS config var tls_config tls.Config = tls.Config{} if !config.Httponly { tls_config.Certificates = []tls.Certificate{config.CertKeyPair} tls_config.NextProtos = []string{"http/1.1"} tls_config.Rand = rand.Reader // Strictly not necessary, should be default } // run backend Start() // run frontend server serve := &http.Server{ Addr: fmt.Sprintf(":%d", config.Configuration.Port), Handler: router, TLSConfig: &tls_config, } if config.Httponly { serve.ListenAndServe() } else { conn, err := net.Listen("tcp", serve.Addr) if err != nil { panic(err) } tlsListener := tls.NewListener(conn, &tls_config) err = serve.Serve(tlsListener) if err != nil { glog.Fatalf("Can not Serve TLS, caused by: %s\n", err) } } return nil }
//Run starts Howler func (svc *Service) Run(cfg ServerSettings) error { config = cfg // save config in global // init gin if !config.Configuration.DebugEnabled { gin.SetMode(gin.ReleaseMode) } var oauth2Endpoint = oauth2.Endpoint{ AuthURL: config.Configuration.AuthURL, TokenURL: config.Configuration.TokenURL, } // Middleware router := gin.New() // use glog for logging router.Use(ginglog.Logger(config.Configuration.LogFlushInterval)) // monitoring GO internals and counter middleware counterAspect := &ginmon.CounterAspect{0} asps := []aspects.Aspect{counterAspect} router.Use(ginmon.CounterHandler(counterAspect)) router.Use(gomonitor.Metrics(9000, asps)) router.Use(ginoauth2.RequestLogger([]string{"uid", "team"}, "data")) // last middleware router.Use(gin.Recovery()) // OAuth2 secured if conf.Oauth2Enabled is set var private *gin.RouterGroup if config.Configuration.Oauth2Enabled { private = router.Group("") var accessTuple = make([]zalando.AccessTuple, len(config.Configuration.AuthorizedUsers)) for i, v := range config.Configuration.AuthorizedUsers { accessTuple[i] = zalando.AccessTuple{Realm: v.Realm, Uid: v.UID, Cn: v.Cn} } zalando.AccessTuples = accessTuple private.Use(ginoauth2.Auth(zalando.UidCheck, oauth2Endpoint)) } router.GET("/", rootHandler) if config.Configuration.Oauth2Enabled { //authenticated routes private.GET("/status", getStatus) private.POST("/events", createEvent) } else { //non authenticated routes router.GET("/status", getStatus) router.POST("/events", createEvent) } // TLS config var tlsConfig = tls.Config{} if !config.Httponly { tlsConfig.Certificates = []tls.Certificate{config.CertKeyPair} tlsConfig.NextProtos = []string{"http/1.1"} tlsConfig.Rand = rand.Reader // Strictly not necessary, should be default } // run frontend server serve := &http.Server{ Addr: fmt.Sprintf(":%d", config.Configuration.Port), Handler: router, TLSConfig: &tlsConfig, } if config.Httponly { serve.ListenAndServe() } else { conn, err := net.Listen("tcp", serve.Addr) if err != nil { panic(err) } tlsListener := tls.NewListener(conn, &tlsConfig) err = serve.Serve(tlsListener) if err != nil { glog.Fatalf("Can not Serve TLS, caused by: %s\n", err) } } return nil }