Skip to content

Instantly share code, notes, and snippets.

@Cephra
Created July 8, 2025 18:41
Show Gist options
  • Select an option

  • Save Cephra/997b6566c9cc8c67bf198d332a8a9a8d to your computer and use it in GitHub Desktop.

Select an option

Save Cephra/997b6566c9cc8c67bf198d332a8a9a8d to your computer and use it in GitHub Desktop.
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