Spaces:
Build error
Build error
File size: 1,944 Bytes
efcdeb3 92fa890 efcdeb3 d06400b efcdeb3 d06400b efcdeb3 d06400b efcdeb3 d06400b efcdeb3 d06400b efcdeb3 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | package main
import (
"net/http"
"os"
"strconv"
"time"
"github.com/AgoraIO-Community/go-tokenbuilder/src/rtctokenbuilder"
"github.com/gin-gonic/gin"
)
type TokenRequest struct {
TokenType string `json:"tokenType"`
Channel string `json:"channel"`
Role string `json:"role"`
Uid string `json:"uid"`
Expire int64 `json:"expire"`
}
func main() {
appID := os.Getenv("APP_ID")
appCert := os.Getenv("APP_CERTIFICATE")
port := os.Getenv("PORT")
if port == "" {
port = "7860"
}
r := gin.Default()
r.GET("/health", func(c *gin.Context) { c.String(200, "ok") })
r.POST("/token/getNew", func(c *gin.Context) {
var req TokenRequest
if err := c.BindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON"})
return
}
if appID == "" || appCert == "" {
c.JSON(http.StatusInternalServerError, gin.H{"error": "missing APP_ID or APP_CERTIFICATE"})
return
}
if req.Channel == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "missing channel"})
return
}
if req.Uid == "" {
req.Uid = "0"
}
if req.Expire <= 0 {
req.Expire = 3600
}
role := rtctokenbuilder.RolePublisher
if req.Role == "subscriber" {
role = rtctokenbuilder.RoleSubscriber
}
expireTime := uint32(time.Now().Unix() + req.Expire)
if uidInt, err := strconv.ParseUint(req.Uid, 10, 32); err == nil {
token, err := rtctokenbuilder.BuildTokenWithUid(appID, appCert, req.Channel, uint32(uidInt), role, expireTime)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"token": token})
return
}
token, err := rtctokenbuilder.BuildTokenWithUserAccount(appID, appCert, req.Channel, req.Uid, role, expireTime)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"token": token})
})
r.Run(":" + port)
}
|