I have a straightforward HTTP server with one route. Can someone help me set up the server so that when I call the route localhost:8090/api//m_test for each connected client, it keeps the random values for each connection separately? I opened two sessions, one in Postman and one in the browser, and I am getting all the values from each client in the previous map. Do I have to configure the server separately or set up channels to separate the data?
The values seem to be appended for each connected client, for example:
{
âcurrentâ: âjZjHwForIZâ,
âpreviousâ: [
âpPevdwCPHDâ,
âpcifcDJtDgâ,
âeHemlejDltâ,
ânlEGpitRVLâ,
âxChOocByrPâ
]
}
Code below:
package main
import (
"github.com/gin-gonic/gin"
"src/src/textfiles"
)
func main() {
router := initRouter()
router.Run(":8090")
}
func initRouter() *gin.Engine {
router := gin.Default()
router.Use(gin.Logger())
router.Use(gin.Recovery())
api := router.Group("/api")
api.GET("/m_test", textfiles.RandomTexts)
return router
}
func CORSMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
c.Header("Access-Control-Allow-Origin", "*")
c.Header("Access-Control-Allow-Credentials", "false")
c.Header("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With")
c.Header("Access-Control-Allow-Methods", "POST,HEAD,PATCH, OPTIONS, GET, PUT")
if c.Request.Method == "OPTIONS" {
c.AbortWithStatus(204)
return
}
c.Next()
}
}
package textfiles
import (
"fmt"
"github.com/gin-gonic/gin"
"math/rand"
"net/http"
"time"
)
var letterRunes = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
var previousLetter = []string{}
//var v =""
func RandomTexts(context *gin.Context) {
v := RandStringRunes(10)
fmt.Println(v)
context.JSON(http.StatusCreated, gin.H{"current": v, "previous": previousLetter})
//context.
previousLetter = append(previousLetter, v)
fmt.Println(previousLetter)
}
func RandStringRunes(n int) string {
b := make([]rune, n)
for i := range b {
b[i] = letterRunes[rand.Intn(len(letterRunes))]
}
return string(b)
}
func init() {
rand.Seed(time.Now().UnixNano())
previousLetter = []string{}
}