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/application/bog.go

102 lines
2.0 KiB
Go

package application
import (
"net/http"
"fmt"
"strconv"
// "io"
"caj-larsson/bog/domain"
"caj-larsson/bog/integration"
)
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 domain.BogFileService
address string
}
func buildFileDataRepository(config FileConfig) domain.FileDataRepository{
fsBogRepo := new(integration.FileSystemBogRepository)
fsBogRepo.Root = config.Path
return fsBogRepo
}
func buildUserAgentRepository(config DatabaseConfig) *integration.SQLiteUserAgentRepository{
if config.Backend != "sqlite" {
panic("Can only handle sqlite")
}
return integration.NewSQLiteUserAgentRepository(config.Connection)
}
3 years ago
func (b *Bog) fileHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
fmt.Fprintf(w, "Hi")
return
}
3 years ago
ref := domain.FileReference {r.URL.Path, r.Header["User-Agent"][0]}
3 years ago
switch r.Method {
case "GET":
bog_file, err := b.file_service.OpenOutFile(ref)
3 years ago
if err == domain.ErrNotExists {
http.NotFound(w, r)
return
}
3 years ago
if err != nil {
panic(err)
}
3 years ago
http.ServeContent(w, r, bog_file.Path(), bog_file.Modified(), bog_file)
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()
fsBogRepo := buildFileDataRepository(config.File)
uaRepo := buildUserAgentRepository(config.Database)
3 years ago
b.file_service = domain.NewBogFileService(
uaRepo, fsBogRepo, 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)
}