Created
May 10, 2023 15:41
-
-
Save Tee-Stark/4cfaca4886fc162521faf248f0da91c5 to your computer and use it in GitHub Desktop.
An implementation of a IP whitelisting system in Golang. Only IP addresses listed in `IPWhitelist` with a value of true will be able to access the restricted endpoint.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/gin-gonic/gin" | |
"go-ip-whitelist/middlewares" | |
"net/http" | |
) | |
var IPWhitelist = map[string]bool{ | |
"127.0.0.1": true, | |
"111.2.3.4": true, | |
"::1": true, | |
} | |
func main() { | |
router := gin.Default() | |
router.GET("/index", func(c *gin.Context) { | |
c.JSON(http.StatusOK, gin.H{ | |
"message": "Welcome to my secure application!", | |
}) | |
}) | |
restrictedPage := router.Group("/") | |
restrictedPage.Use(middlewares.IPWhiteListMiddleware(IPWhitelist)) | |
restrictedPage.GET("/adminZone", func(c *gin.Context) { | |
c.JSON(http.StatusOK, gin.H{ | |
"message": "This endpoint is secured with IP whitelisting!", | |
}) | |
}) | |
router.Run(":3333") // Run on localhost:3333 or 127.0.0.1 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package middlewares | |
import ( | |
"fmt" | |
"github.com/gin-gonic/gin" | |
"net/http" | |
) | |
func IPWhiteListMiddleware(whitelist map[string]bool) gin.HandlerFunc { | |
return func(c *gin.Context) { | |
userIP := c.ClientIP() | |
fmt.Println("Request IP address: ", userIP) | |
if !whitelist[userIP] { | |
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{ | |
"error": "You are not authorized to access this resource!", | |
}) | |
} else { | |
c.Next() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment