Skip to content

Commit

Permalink
Merge pull request #58 from AgoraIO-Community/preflight
Browse files Browse the repository at this point in the history
added preflight support
  • Loading branch information
digitallysavvy authored May 15, 2024
2 parents 3bc7377 + 2ae655a commit 98f5620
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 2 deletions.
41 changes: 39 additions & 2 deletions service/http_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package service
import (
"fmt"
"log"
"net/http"
"strings"

rtmtokenbuilder2 "github.com/AgoraIO-Community/go-tokenbuilder/rtmtokenbuilder"

Expand Down Expand Up @@ -153,8 +155,43 @@ func (s *Service) nocache() gin.HandlerFunc {
c.Header("Cache-Control", "private, no-cache, no-store, must-revalidate")
c.Header("Expires", "-1")
c.Header("Pragma", "no-cache")
if s.allowOrigin != "" {
c.Header("Access-Control-Allow-Origin", s.allowOrigin)
}
}

// Add CORSMiddleware to handle CORS requests and set the necessary headers
func (s *Service) CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
origin := c.Request.Header.Get("Origin")
if !s.isOriginAllowed(origin) {
c.Header("Content-Type", "application/json")
c.JSON(http.StatusForbidden, gin.H{
"error": "Origin not allowed",
})
c.Abort()
return
}
c.Header("Access-Control-Allow-Origin", origin)
c.Header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
c.Header("Access-Control-Allow-Headers", "Origin, Content-Type")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(http.StatusNoContent)
return
}
c.Next()
}
}

func (s *Service) isOriginAllowed(origin string) bool {
if s.allowOrigin == "*" {
return true
}

allowedOrigins := strings.Split(s.allowOrigin, ",")
for _, allowed := range allowedOrigins {
if origin == allowed {
return true
}
}

return false
}
1 change: 1 addition & 0 deletions service/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ func NewService() *Service {
api := gin.Default()

api.Use(s.nocache())
api.Use(s.CORSMiddleware())
api.GET("rtc/:channelName/:role/:tokenType/:rtcuid/", s.getRtcToken)
api.GET("rtm/:rtmuid/", s.getRtmToken)
api.GET("rte/:channelName/:role/:tokenType/:rtcuid/", s.getRtcRtmToken)
Expand Down

0 comments on commit 98f5620

Please sign in to comment.