v1.0.0

Middleware

Last updated


This page shows the three ways to integrate go-ip-sentry and how to wire it into net/http or Gin.

Three Ways to Integrate


OptionSignatureOn failure
HTTPMiddlewarefunc (i *IPGuardian) HTTPMiddleware(next http.Handler) http.HandlerSets Content-Type: application/json, writes the status and {"error": "..."}, and skips next
GinMiddlewarefunc (i *IPGuardian) GinMiddleware() gin.HandlerFuncc.JSON(status, gin.H{"error": ...}) then c.Abort()
Checkfunc (i *IPGuardian) Check(r *http.Request, w http.ResponseWriter) IPGuardianResultUp to the caller

All three have already written the session and device cookies when they pass, so they must run before the handler writes a body.

net/http


  1. mux := http.NewServeMux()
  2. mux.HandleFunc("/api/orders", ordersHandler)
  3. log.Fatal(http.ListenAndServeTLS(":8443", "cert.pem", "key.pem", sentry.HTTPMiddleware(mux)))

Gin


  1. r := gin.New()
  2. r.Use(gin.Recovery())
  3. api := r.Group("/api")
  4. api.Use(sentry.GinMiddleware())
  5. api.GET("/orders", listOrders)
  6. if err := r.RunTLS(":8443", "cert.pem", "key.pem"); err != nil {
  7. log.Fatal(err)
  8. }

To skip paths or call Check directly, see Advanced Middleware Usage.
中文