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_WIDTH_SMALL = 60
IMG_QUALITY = 80 IMG_QUALITY = 80
STATS_CHAN_SIZE = 100 CHAN_SIZE = 100
) )

View file

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

View file

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

View file

@ -10,22 +10,30 @@ import (
"strings" "strings"
) )
func uploadPostHandler(w http.ResponseWriter, r *http.Request, sess *Session) { func InitUpload() {
uploaded := "" uploadChannel = make(chan uploadRequest, CHAN_SIZE)
r.ParseMultipartForm(20000000) go uploadWorker()
filesForm := r.MultipartForm.File["epub"] }
for _, f := range filesForm {
log.Println("File uploaded:", f.Filename) 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() file, err := f.Open()
if err != nil { 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 continue
} }
defer file.Close() defer file.Close()
epub, err := openMultipartEpub(file) epub, err := openMultipartEpub(file)
if err != nil { 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 continue
} }
defer epub.Close() defer epub.Close()
@ -41,12 +49,21 @@ func uploadPostHandler(w http.ResponseWriter, r *http.Request, sess *Session) {
book["file"] = id book["file"] = id
db.InsertBook(book) 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) uploadHandler(w, r, sess)
} }