-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathfile_upload_handler.go
134 lines (117 loc) · 3.86 KB
/
file_upload_handler.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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"strconv"
"github.com/gorilla/mux"
"github.com/swuecho/chat_backend/sqlc_queries"
)
type ChatFileHandler struct {
service *ChatFileService
}
func NewChatFileHandler(sqlc_q *sqlc_queries.Queries) *ChatFileHandler {
ChatFileService := NewChatFileService(sqlc_q)
return &ChatFileHandler{
service: ChatFileService,
}
}
func (h *ChatFileHandler) Register(router *mux.Router) {
router.HandleFunc("/upload", h.ReceiveFile).Methods(http.MethodPost)
router.HandleFunc("/chat_file/{uuid}/list", h.ChatFilesBySessionUUID).Methods(http.MethodGet)
router.HandleFunc("/download/{id}", h.DownloadFile).Methods(http.MethodGet)
router.HandleFunc("/download/{id}", h.DeleteFile).Methods(http.MethodDelete)
}
func (h *ChatFileHandler) ReceiveFile(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(32 << 20) // limit your max input length!
var buf bytes.Buffer
// get formData(session-uuid) from request
// Get the session-uuid from the form data
sessionUUID := r.FormValue("session-uuid")
fmt.Println("Session UUID:", sessionUUID)
// get user-id from request
userID, err := getUserID(r.Context())
if err != nil {
RespondWithError(w, http.StatusBadRequest, err.Error(), err)
return
}
fmt.Println("User ID:", userID)
// in your case file would be fileupload
file, header, err := r.FormFile("file")
if err != nil {
panic(err)
}
defer file.Close()
name := header.Filename
// mimetype
mimeType := header.Header.Get("Content-Type")
fmt.Println("File name:", name, "Mime type:", mimeType)
fmt.Printf("File name: %s\n", name)
// Copy the file data to my buffer
io.Copy(&buf, file)
// inser into chat_file
// check the raw content
// select encode(data, 'escape') as data from chat_file;
chatFile, err := h.service.q.CreateChatFile(r.Context(), sqlc_queries.CreateChatFileParams{
ChatSessionUuid: sessionUUID,
UserID: userID,
Name: name,
Data: buf.Bytes(),
MimeType: mimeType,
})
if err != nil {
RespondWithError(w, http.StatusInternalServerError, err.Error(), err)
return
}
buf.Reset()
// return file name, file id as json
url := fmt.Sprintf("/download/%d", chatFile.ID)
json.NewEncoder(w).Encode(map[string]string{"url": url})
w.WriteHeader(http.StatusOK)
}
func (h *ChatFileHandler) DownloadFile(w http.ResponseWriter, r *http.Request) {
fileID := mux.Vars(r)["id"]
fileIdInt, _ := strconv.ParseInt(fileID, 10, 32)
file, err := h.service.q.GetChatFileByID(r.Context(), int32(fileIdInt))
if err != nil {
RespondWithError(w, http.StatusInternalServerError, err.Error(), err)
return
}
w.Header().Set("Content-Disposition", "attachment; filename=" file.Name)
w.Header().Set("Content-Type", "application/octet-stream")
// w.Header().Set("Content-Disposition",fmt.Sprintf("attachment; filename=%s", file.Name))
w.Write(file.Data)
}
func (h *ChatFileHandler) DeleteFile(w http.ResponseWriter, r *http.Request) {
fileID := mux.Vars(r)["id"]
fileIdInt, _ := strconv.ParseInt(fileID, 10, 32)
_, err := h.service.q.DeleteChatFile(r.Context(), int32(fileIdInt))
if err != nil {
RespondWithError(w, http.StatusInternalServerError, err.Error(), err)
return
}
w.WriteHeader(http.StatusOK)
}
func (h *ChatFileHandler) ChatFilesBySessionUUID(w http.ResponseWriter, r *http.Request) {
sessionUUID := mux.Vars(r)["uuid"]
userID, err := getUserID(r.Context())
if err != nil {
RespondWithError(w, http.StatusInternalServerError, err.Error(), err)
}
chatFiles, err := h.service.q.ListChatFilesBySessionUUID(r.Context(), sqlc_queries.ListChatFilesBySessionUUIDParams{
ChatSessionUuid: sessionUUID,
UserID: userID,
})
if err != nil {
RespondWithError(w, http.StatusInternalServerError, err.Error(), err)
return
}
w.WriteHeader(http.StatusOK)
if len(chatFiles) == 0 {
w.Write([]byte("[]"))
return
}
json.NewEncoder(w).Encode(chatFiles)
}