-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
65 lines (53 loc) · 1.54 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
package main
import (
"encoding/json"
"github.com/incazteca/bookworm/bookworm"
"net/http"
)
const _10MB_LIMIT int64 = (1000 * 10000) + 1
type SuccessRes struct {
FileText string `json:"file_text"`
TotalWordCount int `json:"total_word_count"`
WordCounts map[string]int `json:"word_counts"`
}
type FailRes struct {
ErrorMsg string `json:"error"`
}
func fileUploadHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method == "POST" {
if r.ContentLength > _10MB_LIMIT {
writeError(w, "File upload is limited to 10MB. Please submit a smaller file",
http.StatusRequestEntityTooLarge)
} else {
r.ParseMultipartForm(_10MB_LIMIT)
file, _, err := r.FormFile("file")
if err != nil {
writeError(w, err.Error(), http.StatusInternalServerError)
return
}
defer file.Close()
output, err := bookworm.Parse(file, r.FormValue("filter"))
if err != nil {
writeError(w, err.Error(), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
response := SuccessRes{output.Body, output.TotalWordCount, output.WordCounts}
json.NewEncoder(w).Encode(response)
return
}
} else {
writeError(w, "Page not found", http.StatusNotFound)
return
}
}
func main() {
http.HandleFunc("/file/upload", fileUploadHandler)
http.ListenAndServe(":8080", nil)
}
func writeError(w http.ResponseWriter, errMessage string, errCode int) {
w.WriteHeader(errCode)
failure := FailRes{errMessage}
json.NewEncoder(w).Encode(failure)
}