Midnightar's picture
Update main.go
d06400b verified
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)
}