Implement WriteFileChunk

This commit is contained in:
Felix Geisendörfer 2013-03-19 10:29:06 +01:00
parent b0999b29ca
commit 815964e4a8
2 changed files with 45 additions and 1 deletions

View File

@ -1,6 +1,9 @@
package main package main
import ( import (
"errors"
"fmt"
"io"
"os" "os"
"path" "path"
) )
@ -27,6 +30,47 @@ func (s *DataStore) CreateFile(id string, size int64) error {
return nil return nil
} }
func (s *DataStore) WriteFileChunk(id string, start int64, end int64, src io.Reader) error {
file, err := os.OpenFile(dataPath(id), os.O_WRONLY, 0666)
if err != nil {
return err
}
defer file.Close()
if n, err := file.Seek(start, os.SEEK_SET); err != nil {
return err
} else if n != start {
return errors.New("WriteFileChunk: seek failure")
}
size := end - start + 1
if n, err := io.CopyN(file, src, size); err != nil {
return err
} else if n != size {
return errors.New("WriteFileChunk: partial copy")
}
return s.appendFileLog(id, fmt.Sprintf("%d,%d", start, end))
}
func (s *DataStore) appendFileLog(id string, entry string) error {
logPath := s.logPath(id)
logFile, err := os.OpenFile(logPath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return err
}
defer logFile.Close()
if _, err := logFile.WriteString(entry + "\n"); err != nil {
return err
}
return nil
}
func (s *DataStore) filePath(id string) string { func (s *DataStore) filePath(id string) string {
return path.Join(s.dir, id) return path.Join(s.dir, id)
} }
func (s *DataStore) logPath(id string) string {
return s.filePath(id) + ".log"
}

View File

@ -89,7 +89,7 @@ func postFiles(w http.ResponseWriter, r *http.Request) {
} }
if contentRange.End != -1 { if contentRange.End != -1 {
if err := putFileChunk(id, contentRange.Start, contentRange.End, r.Body); err != nil { if err := dataStore.WriteFileChunk(id, contentRange.Start, contentRange.End, r.Body); err != nil {
// @TODO: Could be a 404 as well // @TODO: Could be a 404 as well
reply(w, http.StatusInternalServerError, err.Error()) reply(w, http.StatusInternalServerError, err.Error())
return return