-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
116 lines (91 loc) · 2.34 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
113
114
115
116
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type information struct {
Name string `json:"name"`
Version string `json:"version"`
}
type listFilesPayload struct {
Name string `json:"name"`
File string `json:"file"`
}
var appInformation = information{
Name: "ZIP Files Application",
Version: "0.1.0",
}
func handleIndex(writer http.ResponseWriter, request *http.Request) {
response, err := json.Marshal(appInformation)
if err != nil {
writer.Header().Set("Content-Type", "text/plain")
writer.Write([]byte(err.Error()))
writer.WriteHeader(http.StatusInternalServerError)
} else {
_, err := writer.Write(response)
if err != nil {
writer.Header().Set("Content-Type", "text/plain")
writer.Write([]byte(err.Error()))
writer.WriteHeader(http.StatusInternalServerError)
} else {
writer.Header().Set("Content-Type", "application/json")
writer.WriteHeader(http.StatusOK)
}
}
}
func handleListFiles(writer http.ResponseWriter, request *http.Request) {
switch request.Method {
case http.MethodPost:
body, err := ioutil.ReadAll(request.Body)
if err != nil {
sendError(writer, err)
return
}
var payload listFilesPayload
err = json.Unmarshal(body, &payload)
if err != nil {
sendError(writer, err)
return
}
err = createFile(payload.Name, payload.File)
if err != nil {
sendError(writer, err)
return
}
defer deleteFile(payload.Name)
zippedFiles, err := listFiles(payload.Name)
if err != nil {
sendError(writer, err)
return
}
resp, err := json.Marshal(zippedFiles)
if err != nil {
sendError(writer, err)
return
}
writer.Header().Set("Content-Type", "application/json")
_, err = writer.Write(resp)
if err != nil {
sendError(writer, err)
return
}
return
default:
writer.WriteHeader(http.StatusMethodNotAllowed)
writer.Header().Set("Content-Type", "text/plain")
writer.Write([]byte(fmt.Sprintf("Http Method %s is not supported", request.Method)))
}
}
func sendError(writer http.ResponseWriter, err error) {
writer.WriteHeader(http.StatusInternalServerError)
writer.Header().Set("Content-Type", "text/plain")
writer.Write([]byte(err.Error()))
}
func main() {
fmt.Println("Starting the server on port 6050")
http.HandleFunc("/", handleIndex)
http.HandleFunc("/listFiles", handleListFiles)
http.ListenAndServe(":6050", nil)
}