Created
July 8, 2025 18:41
-
-
Save Cephra/997b6566c9cc8c67bf198d332a8a9a8d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "math/rand" | |
| "net/http" | |
| "sync" | |
| "time" | |
| "github.com/gin-gonic/gin" | |
| ) | |
| type Job struct { | |
| ID string `json:"id"` | |
| Wait int64 `json:"wait"` | |
| Name string `json:"name"` | |
| Start time.Time `json:"start"` | |
| End time.Time `json:"end"` | |
| } | |
| type JobCreate struct { | |
| Name string `json:"name"` | |
| Wait int64 `json:"wait"` | |
| } | |
| func NewJob(m *sync.Map, wait int64, name string) *Job { | |
| job := &Job{ | |
| ID: fmt.Sprintf("job%d", rand.Intn(999)+int(time.Now().Unix())), | |
| Name: name, | |
| Wait: wait, | |
| } | |
| m.Store(job.ID, job) | |
| go func(job *Job) { | |
| job.Start = time.Now() | |
| time.Sleep(time.Duration(job.Wait) * time.Millisecond) | |
| job.End = time.Now() | |
| }(job) | |
| return job | |
| } | |
| func toJobMap(jobs *sync.Map) map[string]*Job { | |
| jobsMap := map[string]*Job{} | |
| jobs.Range(func(key, value any) bool { | |
| jobsMap[key.(string)] = value.(*Job) | |
| return true | |
| }) | |
| return jobsMap | |
| } | |
| func setupRoutes(r *gin.Engine) *sync.Map { | |
| jobs := &sync.Map{} | |
| r.POST("/api/jobs", func(c *gin.Context) { | |
| var jobCreate JobCreate | |
| if err := c.BindJSON(&jobCreate); err != nil { | |
| c.AbortWithStatus(http.StatusBadRequest) | |
| } else { | |
| c.AsciiJSON(http.StatusOK, NewJob(jobs, jobCreate.Wait, jobCreate.Name)) | |
| } | |
| }) | |
| r.GET("/api/jobs", func(c *gin.Context) { | |
| jobsMap := toJobMap(jobs) | |
| c.AsciiJSON(http.StatusOK, jobsMap) | |
| }) | |
| r.GET("/api/jobs/:id", func(c *gin.Context) { | |
| id := c.Param("id") | |
| if job, found := jobs.Load(id); !found { | |
| c.AsciiJSON(http.StatusNotFound, found) | |
| } else { | |
| c.AsciiJSON(http.StatusOK, job) | |
| } | |
| }) | |
| return jobs | |
| } | |
| func main() { | |
| r := gin.Default() | |
| setupRoutes(r) | |
| r.Run(":8088") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment