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 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 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 }
// 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) } }
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 (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 }