90 lines
1.7 KiB
Go
90 lines
1.7 KiB
Go
|
package main
|
||
|
|
||
|
import (
|
||
|
_ "embed"
|
||
|
"encoding/json"
|
||
|
"net/http"
|
||
|
"os"
|
||
|
"time"
|
||
|
|
||
|
"github.com/gin-gonic/gin"
|
||
|
"github.com/google/uuid"
|
||
|
"github.com/nats-io/nats.go"
|
||
|
"github.com/xeipuuv/gojsonschema"
|
||
|
)
|
||
|
|
||
|
//go:embed "schemas/jsonSchemas/eventsQueueInput.schema.json"
|
||
|
var eventsQueueInputSchema string
|
||
|
|
||
|
func setupRouter() *gin.Engine {
|
||
|
r := gin.Default()
|
||
|
|
||
|
r.GET("/", func(c *gin.Context) {
|
||
|
c.JSON(http.StatusOK, gin.H{
|
||
|
"ok": 1,
|
||
|
"name": "tracker api",
|
||
|
})
|
||
|
})
|
||
|
sl := gojsonschema.NewSchemaLoader()
|
||
|
|
||
|
jsonSchemaLoader := gojsonschema.NewStringLoader(eventsQueueInputSchema)
|
||
|
|
||
|
schema, err := sl.Compile(jsonSchemaLoader)
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
|
||
|
nc, err := nats.Connect(os.Getenv("NATS_URL"), nats.UserInfo(os.Getenv("NATS_USER"), os.Getenv("NATS_PASSWORD")))
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
r.GET("/n.json", func(c *gin.Context) {
|
||
|
|
||
|
id, _ := uuid.NewRandom()
|
||
|
ipAddress := c.ClientIP()
|
||
|
userAgent := c.Request.Header.Get("User-Agent")
|
||
|
createdAt := time.Now().Format(time.RFC3339)
|
||
|
|
||
|
data := gin.H{
|
||
|
"id": id,
|
||
|
"ip": ipAddress,
|
||
|
"userAgent": userAgent,
|
||
|
"createdAt": createdAt,
|
||
|
}
|
||
|
|
||
|
for k, v := range c.Request.URL.Query() {
|
||
|
data[k] = v[0]
|
||
|
}
|
||
|
|
||
|
documentLoader := gojsonschema.NewGoLoader(data)
|
||
|
result, err := schema.Validate(documentLoader)
|
||
|
if err != nil {
|
||
|
panic(err)
|
||
|
}
|
||
|
|
||
|
var errors []string
|
||
|
for _, val := range result.Errors() {
|
||
|
errors = append(errors, val.String())
|
||
|
}
|
||
|
if !result.Valid() {
|
||
|
c.JSON(http.StatusBadRequest, gin.H{"errors": errors})
|
||
|
return
|
||
|
}
|
||
|
|
||
|
jsonData, _ := json.Marshal(data)
|
||
|
nc.Publish("events", []byte(string(jsonData)))
|
||
|
|
||
|
c.JSON(http.StatusOK, gin.H{
|
||
|
"ok": 1,
|
||
|
"id": id,
|
||
|
})
|
||
|
|
||
|
})
|
||
|
return r
|
||
|
}
|
||
|
|
||
|
func main() {
|
||
|
r := setupRouter()
|
||
|
r.Run(":3001")
|
||
|
}
|