Start work on new DataStore type

This commit is contained in:
Felix Geisendörfer 2013-03-19 10:22:13 +01:00
parent 04184d26ed
commit b0999b29ca
3 changed files with 50 additions and 17 deletions

View File

@ -35,21 +35,6 @@ func logPath(fileId string) string {
return dataPath(fileId) + ".log" return dataPath(fileId) + ".log"
} }
func initFile(fileId string, size int64, contentType string) error {
d := dataPath(fileId)
file, err := os.OpenFile(d, os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return err
}
defer file.Close()
if err := file.Truncate(size); err != nil {
return err
}
return nil
}
func putFileChunk(fileId string, start int64, end int64, r io.Reader) error { func putFileChunk(fileId string, start int64, end int64, r io.Reader) error {
d := dataPath(fileId) d := dataPath(fileId)
file, err := os.OpenFile(d, os.O_WRONLY, 0666) file, err := os.OpenFile(d, os.O_WRONLY, 0666)

View File

@ -0,0 +1,32 @@
package main
import (
"os"
"path"
)
type DataStore struct {
dir string
}
func NewDataStore(dir string) *DataStore {
return &DataStore{dir: dir}
}
// @TODO Add support for Content-Type
func (s *DataStore) CreateFile(id string, size int64) error {
file, err := os.OpenFile(s.filePath(id), os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return err
}
defer file.Close()
if err := file.Truncate(size); err != nil {
return err
}
return nil
}
func (s *DataStore) filePath(id string) string {
return path.Join(s.dir, id)
}

View File

@ -5,11 +5,27 @@ import (
"io" "io"
"log" "log"
"net/http" "net/http"
"os"
"path"
"regexp" "regexp"
"strconv" "strconv"
) )
var fileRoute = regexp.MustCompile("^/files/([^/]+)$") var fileRoute = regexp.MustCompile("^/files/([^/]+)$")
var dataStore *DataStore
func init() {
wd, err := os.Getwd()
if err != nil {
panic(err)
}
dataDir = path.Join(wd, "tus_data")
if err := os.MkdirAll(dataDir, 0777); err != nil {
panic(err)
}
dataStore = NewDataStore(dataDir)
}
func serveHttp() error { func serveHttp() error {
http.HandleFunc("/", route) http.HandleFunc("/", route)
@ -67,7 +83,7 @@ func postFiles(w http.ResponseWriter, r *http.Request) {
} }
id := uid() id := uid()
if err := initFile(id, contentRange.Size, contentType); err != nil { if err := dataStore.CreateFile(id, contentRange.Size); err != nil {
reply(w, http.StatusInternalServerError, err.Error()) reply(w, http.StatusInternalServerError, err.Error())
return return
} }
@ -81,7 +97,7 @@ func postFiles(w http.ResponseWriter, r *http.Request) {
} }
w.Header().Set("Location", "/files/"+id) w.Header().Set("Location", "/files/"+id)
setFileRangeHeader(w, id) //setFileRangeHeader(w, id)
w.WriteHeader(http.StatusCreated) w.WriteHeader(http.StatusCreated)
} }