You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
bog/server/bog.go

105 lines
2.2 KiB
Go

package server
import (
"net/http"
"fmt"
"strconv"
// "io"
"caj-larsson/bog/dataswamp"
"caj-larsson/bog/dataswamp/namespace"
"caj-larsson/bog/dataswamp/swampfile"
sql_namespace "caj-larsson/bog/infrastructure/sqlite/namespace"
fs_swampfile "caj-larsson/bog/infrastructure/fs/swampfile"
)
3 years ago
type Router interface {
HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))
ServeHTTP(http.ResponseWriter, *http.Request)
}
type Bog struct {
3 years ago
router Router
file_service dataswamp.SwampFileService
address string
}
func buildFileDataRepository(config FileConfig) swampfile.Repository{
fsSwampfileRepo := new(fs_swampfile.Repository)
fsSwampfileRepo.Root = config.Path
return fsSwampfileRepo
}
func buildUserAgentRepository(config DatabaseConfig) namespace.Repository{
if config.Backend != "sqlite" {
panic("Can only handle sqlite")
}
return sql_namespace.NewRepository(config.Connection)
}
3 years ago
func (b *Bog) fileHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
fmt.Fprintf(w, "Hi")
return
}
ref := swampfile.FileReference {r.URL.Path, r.Header["User-Agent"][0]}
3 years ago
switch r.Method {
case "GET":
swamp_file, err := b.file_service.OpenOutFile(ref)
if err == swampfile.ErrNotExists {
3 years ago
http.NotFound(w, r)
return
}
3 years ago
if err != nil {
panic(err)
}
http.ServeContent(w, r, swamp_file.Path(), swamp_file.Modified(), swamp_file)
3 years ago
case "POST":
fallthrough
case "PUT":
size_str := r.Header["Content-Length"][0]
3 years ago
size, err := strconv.ParseInt(size_str, 10, 64)
if err != nil {
w.WriteHeader(422)
return
}
3 years ago
err = b.file_service.SaveFile(ref, r.Body, size)
3 years ago
if err != nil {
panic(err)
}
3 years ago
}
return
}
3 years ago
func (b *Bog) routes() {
b.router.HandleFunc("/", b.fileHandler)
}
func New(config *Configuration) *Bog {
b := new(Bog)
b.address = config.bindAddress()
fsSwampRepo := buildFileDataRepository(config.File)
uaRepo := buildUserAgentRepository(config.Database)
b.file_service = dataswamp.NewSwampFileService(
uaRepo, fsSwampRepo, config.Quota.ParsedSizeBytes(), config.Quota.ParsedDuration(),
)
3 years ago
b.router = new(http.ServeMux)
b.routes()
return b
}
func (b *Bog) Run() {
3 years ago
http.ListenAndServe(b.address, b.router)
}