-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
112 lines (89 loc) · 1.88 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package main
import (
"encoding/json"
"errors"
"fmt"
"gotask/queue"
"io"
"mime/multipart"
"net/http"
"os"
"reflect"
"strings"
"github.com/gin-gonic/gin"
)
func check(err error) {
if err != nil {
fmt.Println(err)
panic(err)
}
}
type PrintPayload struct {
Text string `json:"text"`
}
type SavePayload struct {
File *multipart.FileHeader
}
func GetStruct[T interface{}](data string) T {
var values T
if err := json.Unmarshal([]byte(data), &values); err != nil {
panic("cannot unmarshal the string")
}
return values
}
func main() {
jobs := &queue.Jobs{
Jobs: queue.JobType{
"print": func(payload string) {
values := GetStruct[PrintPayload](payload)
fmt.Println("working")
fmt.Println(values.Text)
},
"save": func(payload string) {
values := GetStruct[SavePayload](payload)
fmt.Println(values.File.Filename)
file, err := values.File.Open()
check(err)
defer file.Close()
out, err := os.Create("hello.jpg")
check(err)
defer out.Close()
_, err = io.Copy(out, file)
check(err)
},
},
}
go queue.HandleJobs(*jobs)
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
message := c.Query("message")
name := c.Query("name")
jobType := c.Query("type")
queue.CreateNewJob(name, PrintPayload{
Text: message,
}, jobType)
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
r.POST("/save", func(ctx *gin.Context) {
file, err := ctx.FormFile("file")
if err != nil {
ctx.JSON(http.StatusNotFound, gin.H{
"status": "failed",
})
}
ctx.SaveUploadedFile(file, "hello.jpg")
queue.CreateNewJob("save file", SavePayload{
File: file,
}, "save")
})
r.GET("/jobs", func(c *gin.Context) {
jobs := queue.GetAllJobs()
c.JSON(http.StatusOK, gin.H{
"jobs": jobs,
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}