本文整理匯總了Golang中github.com/gin-gonic/gin.Recovery函數的典型用法代碼示例。如果您正苦於以下問題:Golang Recovery函數的具體用法?Golang Recovery怎麽用?Golang Recovery使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了Recovery函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: setup
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
}
示例2: init
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)
}*/
}
示例3: main
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)
}
示例4: startServer
//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
}
示例5: createRouter
func createRouter() {
r = gin.New()
r.Use(gin.Logger())
r.Use(gin.Recovery())
r.Use(corsMiddleware)
r.Use(i18nMiddleware)
}
示例6: main
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()
}
示例7: Run
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")
}
示例8: Load
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
}
示例9: main
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)
}
示例10: run
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")
}
示例11: StartGin
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")
}
示例12: main
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))
}
示例13: main
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")
}
示例14: main
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")
}
示例15: main
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": "manu", "password": "123"})
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")
}