Skip to content

Commit

Permalink
feat(server): Improve form handlers
Browse files Browse the repository at this point in the history
  • Loading branch information
exler committed Sep 11, 2023
1 parent ff48117 commit 053fa37
Show file tree
Hide file tree
Showing 8 changed files with 35 additions and 83 deletions.
4 changes: 2 additions & 2 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func GetStorage(cCtx *cli.Context) (chosenStorage storage.Storage, err error) {
return nil, errors.New("no upload directory specified")
}

chosenStorage, err = storage.NewLocalStorage(udir, cCtx.Duration("retention-time"))
chosenStorage, err = storage.NewLocalStorage(udir)
case "s3":
bucket := cCtx.String("s3-bucket")
region := cCtx.String("s3-region")
Expand All @@ -31,7 +31,7 @@ func GetStorage(cCtx *cli.Context) (chosenStorage storage.Storage, err error) {
sessionToken := cCtx.String("aws-session-token")
endpointUrl := cCtx.String("aws-endpoint-url")

chosenStorage, err = storage.NewS3Storage(accessKey, secretKey, sessionToken, endpointUrl, region, bucket, cCtx.Duration("retention-time"))
chosenStorage, err = storage.NewS3Storage(accessKey, secretKey, sessionToken, endpointUrl, region, bucket)
default:
return nil, errors.New("wrong storage provider")
}
Expand Down
6 changes: 0 additions & 6 deletions cmd/runserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cmd

import (
"log"
"time"

"github.com/exler/fileigloo/logger"
"github.com/exler/fileigloo/server"
Expand All @@ -29,11 +28,6 @@ var serverCmd = &cli.Command{
Value: 20,
EnvVars: []string{"RATE_LIMIT"},
},
&cli.DurationFlag{
Name: "retention-time",
Value: 24 * time.Hour,
EnvVars: []string{"RETENTION_TIME"},
},
&cli.StringFlag{
Name: "storage",
Value: "local",
Expand Down
31 changes: 20 additions & 11 deletions server/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,26 @@ func generateFileId() string {
}

func (s *Server) indexHandler(w http.ResponseWriter, r *http.Request) {
renderTemplate(w, "index", map[string]interface{}{
"retentionTime": s.storage.RetentionTime().String(),
})
renderTemplate(w, "index", map[string]interface{}{})
}

func (s *Server) formHandler(w http.ResponseWriter, r *http.Request) {
if formDefender := r.FormValue("defender"); formDefender != "" {
http.Error(w, http.StatusText(http.StatusTeapot), http.StatusTeapot)
return
}

if formType := r.FormValue("form-type"); formType == "file-upload" {
s.fileUploadHandler(w, r)
} else if formType == "pastebin" {
s.pastebinHandler(w, r)
} else {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
}

func (s *Server) uploadHandler(w http.ResponseWriter, r *http.Request) {
func (s *Server) fileUploadHandler(w http.ResponseWriter, r *http.Request) {
if !ValidateContentType(r.Header) {
http.Error(w, "Request Content-Type must be 'multipart/form-data'", http.StatusBadRequest)
return
Expand Down Expand Up @@ -80,8 +94,7 @@ func (s *Server) uploadHandler(w http.ResponseWriter, r *http.Request) {
s.logger.Info(fmt.Sprintf("New file uploaded [url=%s]", fileUrl))

renderTemplate(w, "index", map[string]interface{}{
"fileUrl": fileUrl,
"retentionTime": s.storage.RetentionTime().String(),
"fileUrl": fileUrl,
})
}

Expand All @@ -90,9 +103,6 @@ func (s *Server) pastebinHandler(w http.ResponseWriter, r *http.Request) {
if pasteContent = r.FormValue("paste"); pasteContent == "" {
http.Error(w, "Paste is empty", http.StatusBadRequest)
return
} else if formDefender := r.FormValue("defender"); formDefender != "" {
http.Error(w, http.StatusText(http.StatusTeapot), http.StatusTeapot)
return
}

buf := []byte(pasteContent)
Expand Down Expand Up @@ -131,8 +141,7 @@ func (s *Server) pastebinHandler(w http.ResponseWriter, r *http.Request) {
s.logger.Info(fmt.Sprintf("New file uploaded [url=%s]", fileUrl))

renderTemplate(w, "index", map[string]interface{}{
"fileUrl": fileUrl,
"retentionTime": s.storage.RetentionTime().String(),
"fileUrl": fileUrl,
})
}

Expand Down
8 changes: 1 addition & 7 deletions server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,7 @@ func (s *Server) Run() {

s.router.Handle("/static/*", fs)
s.router.Get("/", s.indexHandler)
s.router.Post("/upload", s.uploadHandler)
s.router.Post("/pastebin", s.pastebinHandler)
s.router.Post("/", s.formHandler)
s.router.Get("/{view:(?:view)}/{fileId}", s.downloadHandler)
s.router.Get("/{fileId}", s.downloadHandler)

Expand All @@ -93,11 +92,6 @@ func (s *Server) Run() {
}
s.logger.Debug(fmt.Sprintf("Server started [storage=%s]", s.storage.Type()))

err := s.storage.Purge()
if err != nil {
s.logger.Error(err)
}

go func() {
err := srv.ListenAndServe()
if err != nil {
Expand Down
9 changes: 6 additions & 3 deletions server/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@
</div>
{{ end }}

<form id="form-upload" method="POST" action="/upload" enctype="multipart/form-data">
<form id="form-upload" method="POST" action="/" enctype="multipart/form-data">
<section id="upload">
<fieldset>
<legend>File Upload</legend>
Expand All @@ -122,26 +122,29 @@
<input id="file-select-input" type="file" name="file" />
</div>
<div id="upload-button-container">
<input id="file-upload-defender" type="hidden" name="defender" />
<input id="file-upload-form-type" type="hidden" name="form-type" value="file-upload" />
<button id="file-upload-button" type="submit">Upload</button>
<div id="spinner" class="spinner-outer hidden"><div class="spinner-inner"><div></div></div></div>
</div>
</fieldset>
</section>
</form>

<form id="form-pastebin" method="POST" action="/pastebin">
<form id="form-pastebin" method="POST" action="/">
<section id="pastebin">
<fieldset>
<legend>Pastebin</legend>
<textarea id="pastebin-input" autocomplete="off" rows="18" name="paste"></textarea>
<input id="pastebin-defender" type="hidden" name="defender" />
<input id="pastebin-form-type" type="hidden" name="form-type" value="pastebin" />
<button id="pastebin-button" type="submit">Create</button>
</fieldset>
</section>
</form>

<footer>
Copyright (c) {{ now.UTC.Year }} by Kamil Marut | Files are deleted after {{ .retentionTime }} |
Copyright (c) {{ now.UTC.Year }} by Kamil Marut |
<a href="https://github.com/exler/fileigloo" target="_blank" rel="noopener noreferrer">Github</a>
</footer>
</main>
Expand Down
35 changes: 2 additions & 33 deletions storage/local.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,20 @@ import (
"io"
"os"
"path/filepath"
"time"
)

type LocalStorage struct {
Storage
basedir string

retentionTime time.Duration
}

func NewLocalStorage(basedir string, retentionTime time.Duration) (*LocalStorage, error) {
func NewLocalStorage(basedir string) (*LocalStorage, error) {
if basedir[len(basedir)-1:] != "/" {
basedir += "/"
}

storage := &LocalStorage{
basedir: basedir,
retentionTime: retentionTime,
basedir: basedir,
}

return storage, nil
Expand All @@ -35,10 +31,6 @@ func (s *LocalStorage) Type() string {
return "local"
}

func (s *LocalStorage) RetentionTime() time.Duration {
return s.retentionTime
}

func (s *LocalStorage) List(ctx context.Context) (filenames []string, metadata []Metadata, err error) {
err = filepath.WalkDir(s.basedir, func(path string, d os.DirEntry, err error) error {
if err != nil {
Expand Down Expand Up @@ -147,29 +139,6 @@ func (s *LocalStorage) Delete(ctx context.Context, filename string) error {
return nil
}

func (s *LocalStorage) Purge() error {
err := filepath.Walk(s.basedir, func(path string, info os.FileInfo, err error) error {
if err != nil && s.FileNotExists(err) {
return nil
} else if err != nil {
return err
}

if info.IsDir() {
return nil
}

if info.ModTime().Before(time.Now().Add(-s.retentionTime)) {
err = os.Remove(path)
return err
}

return nil
})

return err
}

func (s *LocalStorage) FileNotExists(err error) bool {
if err == nil {
return false
Expand Down
22 changes: 4 additions & 18 deletions storage/s3.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"io"
"strconv"
"time"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
Expand All @@ -19,8 +18,6 @@ type S3Storage struct {
s3 *s3.S3
session *session.Session
bucket string

retentionTime time.Duration
}

func newAWSSession(accessKey, secretKey, sessionToken, endpointUrl, region string) *session.Session {
Expand All @@ -35,18 +32,13 @@ func (s *S3Storage) Type() string {
return "s3"
}

func (s *S3Storage) RetentionTime() time.Duration {
return s.retentionTime
}

func NewS3Storage(accessKey, secretKey, sessionToken, endpointUrl, region, bucket string, retentionTime time.Duration) (*S3Storage, error) {
func NewS3Storage(accessKey, secretKey, sessionToken, endpointUrl, region, bucket string) (*S3Storage, error) {
session := newAWSSession(accessKey, secretKey, sessionToken, endpointUrl, region)

return &S3Storage{
s3: s3.New(session),
session: session,
bucket: bucket,
retentionTime: retentionTime,
s3: s3.New(session),
session: session,
bucket: bucket,
}, nil
}

Expand Down Expand Up @@ -122,7 +114,6 @@ func (s *S3Storage) Put(ctx context.Context, filename string, reader io.Reader,
Key: aws.String(filename),
Body: reader,
Metadata: mMap,
Expires: aws.Time(time.Now().Add(s.retentionTime)),
})

return err
Expand All @@ -138,11 +129,6 @@ func (s *S3Storage) Delete(ctx context.Context, filename string) error {
return err
}

// Noop: S3 has expiration set on file creation
func (s *S3Storage) Purge() error {
return nil
}

func (s *S3Storage) FileNotExists(err error) bool {
if err == nil {
return false
Expand Down
3 changes: 0 additions & 3 deletions storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package storage
import (
"context"
"io"
"time"
)

type Metadata struct {
Expand Down Expand Up @@ -39,8 +38,6 @@ type Storage interface {
GetOnlyMetadata(ctx context.Context, filename string) (metadata Metadata, err error)
Put(ctx context.Context, filename string, reader io.Reader, metadata Metadata) error
Delete(ctx context.Context, filename string) error
Purge() error
FileNotExists(err error) bool
Type() string
RetentionTime() time.Duration
}

0 comments on commit 053fa37

Please sign in to comment.