Skip to content

Instantly share code, notes, and snippets.

@Tee-Stark
Created May 10, 2023 15:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tee-Stark/4cfaca4886fc162521faf248f0da91c5 to your computer and use it in GitHub Desktop.
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.
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
}
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