diff --git a/server/attach.go b/server/attach.go new file mode 100755 index 0000000..80763ae --- /dev/null +++ b/server/attach.go @@ -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 +} diff --git a/server/notes.go b/server/notes.go index 37673b9..48efd6d 100755 --- a/server/notes.go +++ b/server/notes.go @@ -89,7 +89,7 @@ func (s *Server) htmlAttachments(w http.ResponseWriter, urlPath string) { - `, strings.TrimPrefix(urlPath, "/")) + `, strings.TrimPrefix(urlPath, "/notes/")) if config.ReadOnly { form = "" } diff --git a/server/routes.go b/server/routes.go index 6663dd4..c075401 100755 --- a/server/routes.go +++ b/server/routes.go @@ -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 }