Upload files on a separate goroutine

This commit is contained in:
Las Zenow 2013-05-03 00:43:26 +02:00
parent a2c8097dc7
commit 137357cd12
4 changed files with 52 additions and 34 deletions

View file

@ -28,5 +28,5 @@ const (
IMG_WIDTH_SMALL = 60
IMG_QUALITY = 80
STATS_CHAN_SIZE = 100
CHAN_SIZE = 100
)

View file

@ -9,7 +9,7 @@ import (
)
func InitStats() {
statsChannel = make(chan statsRequest, STATS_CHAN_SIZE)
statsChannel = make(chan statsRequest, CHAN_SIZE)
go statsWorker()
}

View file

@ -120,6 +120,7 @@ func main() {
defer db.Close()
InitStats()
InitUpload()
setUpRouter()
panic(http.ListenAndServe(":"+PORT, nil))

View file

@ -10,22 +10,30 @@ import (
"strings"
)
func uploadPostHandler(w http.ResponseWriter, r *http.Request, sess *Session) {
uploaded := ""
r.ParseMultipartForm(20000000)
filesForm := r.MultipartForm.File["epub"]
for _, f := range filesForm {
log.Println("File uploaded:", f.Filename)
func InitUpload() {
uploadChannel = make(chan uploadRequest, CHAN_SIZE)
go uploadWorker()
}
var uploadChannel chan uploadRequest
type uploadRequest struct {
epubs []*multipart.FileHeader
}
func uploadWorker() {
for req := range uploadChannel {
for _, f := range req.epubs {
file, err := f.Open()
if err != nil {
sess.Notify("Problem uploading!", "The file '"+f.Filename+"' is not a well formed epub: "+err.Error(), "error")
log.Println("Can not open uploaded file", f.Filename, ":", err)
continue
}
defer file.Close()
epub, err := openMultipartEpub(file)
if err != nil {
sess.Notify("Problem uploading!", "The file '"+f.Filename+"' is not a well formed epub: "+err.Error(), "error")
log.Println("Not valid epub uploaded file", f.Filename, ":", err)
continue
}
defer epub.Close()
@ -41,12 +49,21 @@ func uploadPostHandler(w http.ResponseWriter, r *http.Request, sess *Session) {
book["file"] = id
db.InsertBook(book)
uploaded += " '" + title + "'"
log.Println("File uploaded:", f.Filename)
}
if uploaded != "" {
sess.Notify("Upload successful!", "Added the books:"+uploaded+". Thank you for your contribution", "success")
}
}
func uploadPostHandler(w http.ResponseWriter, r *http.Request, sess *Session) {
r.ParseMultipartForm(20000000)
filesForm := r.MultipartForm.File["epub"]
uploadChannel <- uploadRequest{filesForm}
if len(filesForm) > 0 {
sess.Notify("Upload successful!", "Thank you for your contribution", "success")
} else {
sess.Notify("Upload problem!", "No books where uploaded.", "error")
}
uploadHandler(w, r, sess)
}