func setup() *gin.Engine { runtime.GOMAXPROCS(runtime.NumCPU()) if _, err := database.InitDb(); err != nil { panic(err) } app := gin.New() app.Use(func(c *gin.Context) { c.Set(config.SecretKey, config.GetSecret()) c.Next() }) if config.GetEnv() == config.EnvProduction { app.Use(middleware.Recovery()) } else { app.Use(gin.Recovery()) } if config.GetEnv() == config.EnvTesting { gin.SetMode(gin.TestMode) } else { app.Use(gin.Logger()) } app.Use(middleware.ErrorHandler()) //Set up api v1 routeV1(app) return app }
func init() { // Starts a new Gin instance with no middle-ware r := gin.Default() r.Use(log.Logger()) r.Use(gin.Recovery()) s_store := sessions.NewCookieStore([]byte("secret")) r.Use(sessions.Sessions("mysession", s_store)) r.LoadHTMLGlob("templates/*") r.Static("/assets", "./assets") r.GET("/load", LoadConst) r.POST("/point", Point) r.GET("/profile/:prof_id/:det_id", GetProfile) r.POST("/profile", PutProfile) r.DELETE("/profile/:prof_id/:det_id", DeleteProfile) r.GET("/profile", ListProfile) r.GET("/load/sampleprofile/:prof_id/:det_id", service.PutSampleProfile) r.POST("/comments", PutComments) r.GET("/consti/:id", FilterConstiProfile) r.GET("/", Home) r.GET("/admin", Admin) r.GET("/login", login.Login) r.GET("/FBLogin", social.FBLogin) r.GET("/GoogleLogin", social.GoogleLogin) r.GET("/TestLogin", auth.TestLogin) r.GET("/logout", auth.Logout) r.POST("/admin/upload", store.Upload) r.GET("/admin/bloburl", store.UploadUrl) r.GET("/serve/:blobKey", store.GetServingUrl) r.GET("/likes/:prof_id/:det_id", service.AddLikes) r.GET("/unlikes/:prof_id/:det_id", service.AddUnLikes) r.GET("/me", GetUser) r.POST("/volunteer", service.SendVolunteerRequest) r.GET("/volunteer/:req_id", service.ProcessVolunteerRequest) r.GET("/user", service.ListUser) r.GET("/user/:user_id", service.GetUser) r.POST("/user", service.UpdateUser) r.GET("/about", About) http.Handle("/", r) //appengine.Main() /* authorized := r.Group("/write") authorized.Use(Auth()) { authorized.POST("/login", loginEndpoint) }*/ }
func main() { r := gin.New() r.Use(gin.Recovery(), gin.LoggerWithWriter(setting.LogIO)) r.Use(func(c *gin.Context) { // Run this on all requests // Should be moved to a proper middleware c.Writer.Header().Set("Access-Control-Allow-Origin", "*") c.Writer.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization") c.Next() }) gin.SetMode(setting.GinMode) r.OPTIONS("/*cors", func(c *gin.Context) { // Empty 200 response }) user := r.Group("/user") { user.POST("/token", handlers.Token) user.POST("/register", handlers.Register) } authorized := r.Group("/api", middlewares.Auth(handlers.MySigningKey)) authorized.POST("/balance", handlers.Balance) r.Run(setting.AppCfg.HttpPort) }
func createRouter() { r = gin.New() r.Use(gin.Logger()) r.Use(gin.Recovery()) r.Use(corsMiddleware) r.Use(i18nMiddleware) }
func main() { runtime.GOMAXPROCS(runtime.NumCPU()) role := config.mustGetString("postgres", "role") database := config.mustGetString("postgres", "database") ip := config.mustGetString("postgres", "ip") password := config.mustGetString("postgres", "password") services.InitDBConnection(role, password, database, ip) api_key := config.mustGetString("parsemap", "api_key") r := gin.New() r.Use(gzip.Gzip(gzip.DefaultCompression)) r.Use(gin.Logger()) r.Use(gin.Recovery()) r.Use(gin.ErrorLogger()) v2 := r.Group("/v2") services.GetHandlersV2(v2, api_key) var wg sync.WaitGroup wg.Add(2) go startServer(r, &wg) go startTLSServer(r, &wg) wg.Wait() }
//run starts the webserver func (v *Vault) startServer() error { glog.Infof("Starting local server\n") router := gin.New() //TODO initialize configurations, correct middlewares, https/http router.Use(ginglog.Logger(5)) //5 seconds router.Use(gin.Recovery()) //setting up https by default var tlsConfig = tls.Config{} keypair, err := tls.LoadX509KeyPair(v.config["tlsCertfilePath"], v.config["tlsKeyfilePath"]) if err != nil { fmt.Printf("ERR: Could not load X509 KeyPair, caused by: %s\n", err) os.Exit(1) //exit explicitely as we choose a fail fast approach } tlsConfig.Certificates = []tls.Certificate{keypair} tlsConfig.NextProtos = []string{"http/1.1"} tlsConfig.Rand = rand.Reader router.GET("/secret/:appID", v.getSecret) serve := &http.Server{ Addr: fmt.Sprintf(":%s", v.config["serverPort"]), Handler: router, TLSConfig: &tlsConfig, } err = serve.ListenAndServe() if err != nil { glog.Errorf("Cannot start server for Cubbyhole tokens distribution\n") } return err }
func Run() { r := gin.New() // Global middlewares // If use gin.Logger middlewares, it send duplicated request. switch config.Environment { case "DEVELOPMENT": r.Use(gin.Logger()) case "TEST": r.Use(log.AccessLogger()) case "PRODUCTION": r.Use(log.AccessLogger()) } r.Use(gin.Recovery()) r.Use(CORSMiddleware()) switch config.Frontend { case "CanJS": canjs.LoadPage(r) default: canjs.LoadPage(r) } api.RouteAPI(r) // Listen and server on 0.0.0.0:3001 // r.Run("localhost:3001") r.Run(":3001") }
func Load(middleware ...gin.HandlerFunc) http.Handler { e := gin.New() e.Use(gin.Recovery()) e.SetHTMLTemplate(template.Template()) e.StaticFS("/static", static.FileSystem()) e.Use(header.NoCache) e.Use(header.Options) e.Use(header.Secure) e.Use(middleware...) e.Use(session.SetUser) e.GET("/api/user", session.UserMust, api.GetUser) e.GET("/api/user/teams", session.UserMust, api.GetTeams) e.GET("/api/user/repos", session.UserMust, api.GetRepos) e.GET("/api/repos/:owner/:repo", session.UserMust, access.RepoPull, api.GetRepo) e.POST("/api/repos/:owner/:repo", session.UserMust, access.RepoAdmin, api.PostRepo) e.DELETE("/api/repos/:owner/:repo", session.UserMust, access.RepoAdmin, api.DeleteRepo) e.GET("/api/repos/:owner/:repo/maintainers", session.UserMust, access.RepoPull, api.GetMaintainer) e.GET("/api/repos/:owner/:repo/maintainers/:org", session.UserMust, access.RepoPull, api.GetMaintainerOrg) e.POST("/hook", web.Hook) e.GET("/login", web.Login) e.POST("/login", web.LoginToken) e.GET("/logout", web.Logout) e.NoRoute(web.Index) return e }
func main() { err := modem.Connect() if err != nil { log.Printf("ConnectModem: error connecting to %s, %s\r\n", modem.DeviceId, err) log.Printf("commport: %s\r\n", config.CommPort) log.Printf("baud: %d\r\n", config.Baud) os.Exit(1) } err = modem.InitialiseModem() if err != nil { log.Printf("InitModem: error initialising %s, %s\r\n", modem.DeviceId, err) } // Creates a router without any middleware by default //gin.SetMode(gin.ReleaseMode) r := gin.New() // Global middlewares r.Use(gin.Logger()) r.Use(gin.Recovery()) r.Use(SetJellyBeans()) api := r.Group("/api") { api.GET("/sms", index) api.POST("/sms", sendSMS) } go worker() // Listen and server on 0.0.0.0:8951 r.Run(bindaddress) }
func run() { logFile, logErr := os.OpenFile(*logFileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666) if logErr != nil { fmt.Println("Fail to find", *logFile, "cServer start Failed") os.Exit(1) } log.SetOutput(logFile) log.Printf("CM Server Start") CACHE = NewCache(PATH + "cache") defer CACHE.Close() CACHE.All() gin.SetMode(gin.ReleaseMode) //g := gin.Default() g := gin.New() g.Use(gin.Recovery()) g.Use(gin.LoggerWithWriter(logFile)) g.Use(gzip.Gzip(gzip.DefaultCompression)) g.POST("/cm/settings", postSettings) g.GET("/cm/settings", getSettings) g.GET("/cm/menus", func(c *gin.Context) { c.JSON(http.StatusOK, CACHE.menus) }) g.NoRoute(func(c *gin.Context) { c.String(http.StatusNotFound, "404") }) g.Run(":8011") }
func StartGin() { gin.SetMode(gin.ReleaseMode) router := gin.New() gin.Logger() router.Use(rateLimit, gin.Recovery()) router.Use(gin.Logger()) router.LoadHTMLGlob("resources/*.templ.html") router.Static("/static", "resources/static") router.GET("/", MyBenchLogger(), index) router.GET("/auth", authentication.RequireTokenAuthentication(), index) router.POST("/test", controllers.Login) router.GET("/room/:name", roomGET) router.POST("/room-post/:roomid", roomPOST) router.GET("/stream/:roomid", streamRoom) //mongodb user create uc := user_controllers.NewUserController(getSession()) router.GET("/user", uc.GetUser) router.GET("/message", uc.GetMessage) router.POST("/message", uc.CreateMessage) router.POST("/user", uc.CreateUser) router.DELETE("/user/:id", uc.RemoveUser) router.Run(":5001") }
func main() { r.SetVerbose(true) defer utils.Recover() utils.ListenSignals() utils.Liveness() if os.Getenv("DEBUG_N") != "true" { gin.SetMode(gin.ReleaseMode) } engine := gin.New() engine.Use(gin.Recovery()) engine.Use(func() gin.HandlerFunc { return func(c *gin.Context) { defer c.Next() log.Info(c.Request.Method, c.Request.URL.Path, c.Writer.Status()) } }()) api.Initialize(engine) engine.Run(config.Get(config.KEY_API_PORT)) }
func main() { zalando.AccessTuples = []zalando.AccessTuple{{"teams", "Techmonkeys", "Platform Engineering / System"}} flag.Parse() router := gin.New() router.Use(ginglog.Logger(3 * time.Second)) router.Use(ginoauth2.RequestLogger([]string{"uid"}, "data")) router.Use(gin.Recovery()) public := router.Group("/api") public.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "Hello to public world"}) }) private := router.Group("/api/private") privateUser := router.Group("/api/privateUser") glog.Infof("Register allowed users: %+v and groups: %+v", USERS, zalando.AccessTuples) private.Use(ginoauth2.Auth(zalando.GroupCheck, zalando.OAuth2Endpoint)) privateUser.Use(ginoauth2.Auth(zalando.UidCheck, zalando.OAuth2Endpoint)) private.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "Hello from private for groups"}) }) privateUser.GET("/", func(c *gin.Context) { c.JSON(200, gin.H{"message": "Hello from private for users"}) }) glog.Info("bootstrapped application") router.Run(":8081") }
func main() { r = gin.Default() // Global middleware r.Use(gin.Logger()) r.Use(gin.Recovery()) r.Static("/assets", "./assets") r.LoadHTMLGlob("view/*") // Simple group: v1 v1 := r.Group("/") { v1.GET("/", home.Dispatch) } // Simple group: v2 v2 := r.Group("/api") { v2.GET("/login", api.Login) v2.GET("/mail/list", api.MailList) v2.GET("/mail/detail", api.MailDetail) v2.GET("/mail/box", api.MailBox) v2.GET("/mail/send", api.MailSend) v2.GET("/mail/set", api.MailSet) } r.Run(":8081") }
func main() { router := gin.New() router.LoadHTMLGlob("templates/*") router.Use(gin.Logger()) router.Use(gin.Recovery()) v1 := router.Group("/v1") // Example for binding JSON ({"user": "******", "password": "******"}) v1.POST("/loginJSON", func(c *gin.Context) { var json Login if c.BindJSON(&json) == nil { if json.User == "manu" && json.Password == "123" { c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) } else { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"}) } } }) router.GET("/login", func(c *gin.Context) { c.HTML(http.StatusOK, "loginform.tmpl", gin.H{ "Title": "Login Page", }) }) // Example for binding a HTML form (user=manu&password=123) v1.POST("/loginForm", Hello(), Lolo) // Listen and server on 0.0.0.0:8080 router.Run(":8080") }
// NewOpenVPNAuthd creates a new service for shipping out the openvpn config func NewOpenVPNAuthd(cfg *AuthConfig) (OpenVPNAuthd, error) { //var err error glog.Infof("creating a new openvpn authd service, config: %s", cfg) service := new(openvpnAuthd) service.config = cfg // step: create the vault client glog.V(3).Infof("creating the vault client, address: %s, username: %s", cfg.VaultURL, cfg.VaultUsername) client, err := NewVaultClient(cfg.VaultURL, cfg.VaultCaFile, cfg.VaultTLSVerify) if err != nil { return nil, fmt.Errorf("failed to create a vault client, error: %s", err) } service.vault = client // step: attempt to authenticate to vault err = client.Authenticate(cfg.VaultUsername, cfg.VaultPassword) if err != nil { return nil, fmt.Errorf("failed to authenticate to vault, error: %s", err) } // step: create the gin router router := gin.New() router.LoadHTMLGlob("templates/*") router.Use(gin.Logger()) router.Use(gin.Recovery()) router.GET("/health", service.healthHandler) router.GET("/", service.openVPNHandler) service.router = router return service, nil }
// 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 main() { // nuCPU := runtime.NumCPU() // runtime.GOMAXPROCS(nuCPU) // fmt.Printf("Running with %d CPUs\n", nuCPU) if !configs.Debug { gin.SetMode(gin.ReleaseMode) } if configs.Debug { r.Use(gin.Logger()) } r.Use(gin.Recovery()) r.Static("/static", "./static") // r.LoadHTMLGlob("templates/**/*.html") // r.GET("/", indexPageHandler) r.GET("/", loginRequired(indexPageHandler)) r.GET(login_page, loginHandler) r.POST(login_page, authLoginHandler) r.POST("/logout", logoutHandler) r.GET("/upload", loginRequired(upload)) r.POST("/upload", loginRequired(upload)) r.GET("/page/:link", pageRouter) r.NoRoute(func(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{"code": "PAGE_NOT_FOUND", "message": "Page not found"}) }) // r.Run(":8080") // listen and serve on 0.0.0.0:8080 http.ListenAndServe(":8080", CSRF(r)) // http.ListenAndServeTLS(":8080", "/etc/nginx/ssl/nginx.crt", "/etc/nginx/ssl/nginx.key", CSRF(r)) }
func main() { ROOT_DIR, _ = osext.ExecutableFolder() config.LoadConfig(ge.BuildFullPath(ROOT_DIR, "config.json")) GE = ge.NewGalaxyEmpires(ge.BuildFullPath(ROOT_DIR, "data"), ge.CoordinatesStruct{1, 15, 5}) r := gin.New() r.Use(gin.Logger()) r.Use(gin.Recovery()) r.Use(middleware.Errors("", "", nil)) debug.AssignDebugHandlers(r.Group("/debug")) handlers.NewAccountHandler(r.Group("/account"), GE) handlers.NewPlayerHandler(r.Group("/player", middleware.Authentication([]byte(config.Config.Key))), GE) handlers.NewPlanetHandler(r.Group("/planet", middleware.Authentication([]byte(config.Config.Key))), GE) r.Static("/assets", ROOT_DIR+"/web/assets") r.StaticFile("/", ROOT_DIR+"/web/index.html") if err := r.Run(":" + config.Config.Port); err != nil { panic(err) } }
func main() { flag.Parse() common.Info("initializing metric http endpoint") connector, err := common.BuildRabbitMQConnector(*rabbitHost, *rabbitPort, *rabbitUser, *rabbitPassword, *rabbitExchange) if err != nil { log.Fatalln("error", err) } bindTo := fmt.Sprintf(":%d", *serverPort) common.Info("binding to:", bindTo) service := metricsService{connector: connector} gin.SetMode(gin.ReleaseMode) r := gin.New() r.Use(gin.Recovery()) r.POST("/metrics", service.createMetric) r.GET("/debug/vars", expvar.Handler()) if err := r.Run(bindTo); err != nil { log.Fatalln(err) } }
func main() { Logger.Formatter = new(logrus.JSONFormatter) // init db := InitDatabase("./myapp.db") defer db.Close() r := gin.Default() // middleware r.Use(func(c *gin.Context) { c.Set("DB", db) c.Next() }) r.Use(gin.Logger()) r.Use(gin.Recovery()) r.Use(SetProperties) // handlers r.GET("/users/", ListUsers) r.GET("/users/:name", GetUser) r.POST("/users/:name", RegisterUser) r.PUT("/users/:name", UpdateUserInfo) r.DELETE("/users/:name", DeleteUserInfo) r.Run(":8000") }
func main() { // Set Working direcotry _, filename, _, _ := runtime.Caller(0) var dir, _ = filepath.Split(filename) os.Chdir(dir) // Echo instance r := gin.New() // Global middleware r.Use(gin.Logger()) r.Use(gin.Recovery()) // Database r.Use(config.DbMw()) // Sessions r.Use(config.SessionMw()) // Templates // config.SetRenderer(e) // Routes config.Routes(r) // Start server var port = ":3333" log.Println("HTTP Server running on port :3333!") r.Run(port) }
func Server() { runtime.GOMAXPROCS(runtime.NumCPU()) if _, err := database.InitDb(); err != nil { panic(err) } app := gin.New() app.Use(func(c *gin.Context) { c.Set(config.SecretKey, config.GetSecret()) c.Next() }) if config.GetEnv() != config.EnvProduction { app.Use(gin.Logger()) app.Use(gin.Recovery()) } else { app.Use(middleware.Recovery()) } app.Use(middleware.ErrorHandler()) app.Static("/public", "./public") //Set up api v1 setupApiV1(app) env := config.GetEnvValue() app.Run(env.Server.Host + ":" + strconv.Itoa(env.Server.Port)) }
func main() { // Creates a router without any middleware by default r := gin.New() // Global middlewares r.Use(gin.Recovery()) // Setup templates r.LoadHTMLGlob("templates/*") // Action handler r.GET("/:title", func(c *gin.Context) { title := c.Params.ByName("title") members := []gin.H{ {"Name": "Chris McCord"}, {"Name": "Matt Sears"}, {"Name": "David Stump"}, {"Name": "Ricardo Thompson"}} c.HTML(200, "layout.tmpl", gin.H{"Title": title, "Members": members}) }) // manually get port from environment port := os.Getenv("PORT") if port == "" { port = ":3000" } else { port = ":" + port } // Run the server fmt.Println("Starting on port " + port) r.Run(port) }
func main() { router := gin.New() // Global middleware router.Use(gin.Logger()) router.Use(gin.Recovery()) router.GET("/animated.gif", animatedgif) router.Run("0.0.0.0:8000") }
func (s *Server) SeDefaultMiddleware() error { s.Router.Use(gin.Logger()) s.Router.Use(gin.Recovery()) s.Router.Use(middleware.Cors()) s.Router.Use(middleware.Application(s.Config)) return nil }
func main() { e := gin.New() e.Use(gin.Logger()) e.Use(gin.Recovery()) e.GET("/gui/*filepath", static) e.GET("/api/stats", stats) e.Run(":1488") }
func init() { router := gin.New() router.Use(gin.Logger()) router.Use(gin.Recovery()) router.Use() }
func StartServer() error { router := gin.New() router.Use(gin.Logger()) router.Use(gin.Recovery()) prepareRoutes(router) router.Run(":8080") return nil }
func NewWebServer() *WebServer { server := new(WebServer) gin.SetMode(gin.ReleaseMode) server.Router = gin.New() server.Router.Use(gin.Recovery()) return server }