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 (u *UserResource) Register(usergroup *gin.RouterGroup) { usergroup.OPTIONS("login") usergroup.GET("login", u.login) usergroup.GET("find/:user-id", u.findUser) usergroup.PUT("update/:user-id", u.updateUser) usergroup.DELETE("remove/:user-id", u.removeUser) }
func Routes(oauth *oauth2.Config, r *gin.RouterGroup) { passportOauth = oauth r.GET("/login", func(c *gin.Context) { Login(oauth, c) }) }
// Setup configures how to handle routes func Setup(group *gin.RouterGroup, db *db.DB) { group.Use() { group.GET("/", renderItemHandler(db)) group.GET("/:shortcode", renderItemHandler(db)) } }
// 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) }
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) }
// 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) } }
func NewSshController(s *gin.RouterGroup) *SshController { ctl := &SshController{} s.GET("/ssh/public-key", ctl.getPublicKey) return ctl }
func NewDeploymentController(s *gin.RouterGroup) *DeploymentController { ctl := &DeploymentController{} s.GET("/apps/:id/deploy/:deploy_id", ctl.getDeployment) s.GET("/apps/:id/deploy", ctl.getDeploymentList) return ctl }
// 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)) } }
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 }
// 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 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 RealMain(routerGroup *gin.RouterGroup) { routerGroup.GET("/users", func(c *gin.Context) { data := User{ ID: 1, Name: "Widnyana", Email: "*****@*****.**", } c.JSON(200, data) }) }
// initRoutesSystem initialized routes for System Controller func initRoutesSystem(router *gin.RouterGroup, checkPassword gin.HandlerFunc) { systemCtrl := &SystemController{} router.GET("/version", systemCtrl.GetVersion) router.GET("/capabilities", systemCtrl.GetCapabilites) admin := router.Group("/system") admin.Use(checkPassword, CheckAdmin()) { admin.GET("/cache/clean", systemCtrl.CleanCache) admin.GET("/cache/info", systemCtrl.CleanInfo) } }
// 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 (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) }
func mount(r *gin.RouterGroup) { r.GET("", func(c *gin.Context) { s := c.MustGet("store").(*store) y, w := getISOWeek(c) if data, found := s.GetHoroscopes(y, w); found { c.Data(http.StatusOK, "application/json", data) } else { c.AbortWithStatus(http.StatusNotFound) } }) r.GET("/:sign", func(c *gin.Context) { s := c.MustGet("store").(*store) y, w := getISOWeek(c) if data, found := s.GetHoroscope(y, w, c.Param("sign")); found { c.Data(http.StatusOK, "application/json", data) } else { c.AbortWithStatus(http.StatusNotFound) } }) }
func (s *Storage) RegisterRouterGroup(group *gin.RouterGroup) { group.GET("/*key", func(c *gin.Context) { var data interface{} key := strings.Trim(c.Param("key"), "/") err := s.Get(key, &data) if err != nil { if _, ok := err.(KeyNotFound); ok { c.JSON(404, shared.HttpError{"Key not found.", nil}) return } c.JSON(500, shared.HttpError{"Failed to read value from datastore.", err}) return } c.JSON(200, data) }) group.PUT("/*key", func(c *gin.Context) { var data interface{} err := c.BindJSON(&data) if err != nil { c.JSON(400, shared.HttpError{"Failed to decode request body.", err}) return } key := strings.Trim(c.Param("key"), "/") log.Printf(key) err = s.Set(key, data) if err != nil { c.JSON(500, shared.HttpError{"Failed to write value to datastore.", err}) return } }) }
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 }
// Bind attaches api routes func (api *API) Bind(group *gin.RouterGroup) { group.GET("/v1/conf", api.ConfHandler) }
func Index(router *gin.RouterGroup) { router.GET("/", handler.Index) router.GET("/ping", handler.Pong) }
func AddFlightRoutes(group *gin.RouterGroup) { group.GET("/search", searchFlightInCity) group.GET("/review", getFlightReview) }
func AddHotelRoutes(group *gin.RouterGroup) { group.GET("/search", searchHotelInCity) group.GET("/review", getHotelReview) }
func (svc *Service) Run(cfg Config) error { cfg = cfg // save config in global // init gin if !cfg.Debug { gin.SetMode(gin.ReleaseMode) } // Middleware router := gin.New() // use glog for logging router.Use(ginglog.Logger(cfg.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)) // last middleware router.Use(gin.Recovery()) svc.ProxyCfg = conf.New() glog.Infof("svc config: %+v", svc.ProxyCfg) // OAuth2 secured if conf.Oauth2Enabled is set var private *gin.RouterGroup if cfg.Oauth2Enabled { zalando.AccessTuples = []zalando.AccessTuple{{"employees", "sszuecs", "Sandor Szücs"}, {"employees", "njuettner", "Nick Jüttner"}, {"employees", "rdifazio", "Raffaele Di Fazio"}} private = router.Group("") private.Use(ginoauth2.Auth(zalando.UidCheck, cfg.OAuth2Endpoints)) } // // Handlers // if cfg.Oauth2Enabled { private.GET("/", svc.rootHandler) private.GET("/sum/:name", svc.sumHandler) private.GET("/eql/:name", svc.eqlHandler) } else { router.GET("/", svc.rootHandler) router.GET("/sum/:name", svc.sumHandler) router.GET("/eql/:name", svc.eqlHandler) } // TLS config var tls_config tls.Config = tls.Config{} if !cfg.Httponly { tls_config.Certificates = []tls.Certificate{cfg.CertKeyPair} tls_config.NextProtos = []string{"http/1.1"} tls_config.Rand = rand.Reader // Strictly not necessary, should be default } // run frontend server serve := &http.Server{ Addr: fmt.Sprintf(":%d", cfg.SvcPort), Handler: router, TLSConfig: &tls_config, } if cfg.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 }
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 }
func (api __api__) bind(r *gin.RouterGroup) { r.GET("/users/:username", api.username) }