impl attach

master
Bel LaPointe 2021-02-25 17:00:22 -06:00
parent 014076dd06
commit 8fefc60f6b
3 changed files with 59 additions and 2 deletions

48
server/attach.go Executable file
View File

@ -0,0 +1,48 @@
package server
import (
"errors"
"io"
"local/notes-server/filetree"
"net/http"
"os"
"path"
"strings"
)
func (s *Server) attach(w http.ResponseWriter, r *http.Request) {
if err := s._attach(w, r); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func (s *Server) _attach(w http.ResponseWriter, r *http.Request) error {
r.ParseMultipartForm(100 << 20)
file, handler, err := r.FormFile("file")
if err != nil {
return err
}
defer file.Close()
ft := filetree.NewPathFromURL(r.URL.Path)
local := ft.Local
target := path.Join(path.Dir(local), "."+path.Base(local)+".attachments", handler.Filename)
os.MkdirAll(path.Dir(target), os.ModePerm)
if fi, err := os.Stat(target); err != nil && !os.IsNotExist(err) {
return err
} else if err == nil && fi.IsDir() {
return errors.New("invalid path")
}
f, err := os.Create(target)
if err != nil {
return err
}
defer f.Close()
if _, err := io.Copy(f, file); err != nil {
return err
}
http.Redirect(w, r, "/notes"+strings.TrimPrefix(ft.HREF, "/attach"), http.StatusSeeOther)
return nil
}

View File

@ -89,7 +89,7 @@ func (s *Server) htmlAttachments(w http.ResponseWriter, urlPath string) {
<input type="file" name="file" required/>
<input type="submit" value="+"/>
</form>
`, strings.TrimPrefix(urlPath, "/"))
`, strings.TrimPrefix(urlPath, "/notes/"))
if config.ReadOnly {
form = ""
}

View File

@ -33,6 +33,9 @@ func (s *Server) Routes() error {
fmt.Sprintf("create/%s%s", wildcard, wildcard): {
handler: s.gzip(s.authenticate(s.create)),
},
fmt.Sprintf("attach/%s%s", wildcard, wildcard): {
handler: s.gzip(s.authenticate(s.attach)),
},
fmt.Sprintf("comment/%s%s", wildcard, wildcard): {
handler: s.gzip(s.authenticate(s.comment)),
},
@ -43,7 +46,13 @@ func (s *Server) Routes() error {
for path, endpoint := range endpoints {
if config.ReadOnly {
for _, prefix := range []string{"edit/", "delete/", "delete/", "create/", "submit/"} {
for _, prefix := range []string{
"edit/",
"delete/",
"create/",
"submit/",
"attach/",
} {
if strings.HasPrefix(path, prefix) {
endpoint.handler = http.NotFound
}