Midnightar commited on
Commit
efcdeb3
·
verified ·
1 Parent(s): 478bc36

Create main.go

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