diff --git a/server/submit.go b/server/submit.go index 4bb7c29..0873eb3 100755 --- a/server/submit.go +++ b/server/submit.go @@ -1,6 +1,8 @@ package server import ( + "bytes" + "fmt" "html" "local/notes-server/filetree" "net/http" @@ -16,6 +18,7 @@ func (s *Server) submit(w http.ResponseWriter, r *http.Request) { content := r.FormValue("content") content = html.UnescapeString(content) content = strings.ReplaceAll(content, "\r", "") + content = trimLines(content) err := s.Notes.Submit(r.URL.Path, content) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) @@ -25,3 +28,12 @@ func (s *Server) submit(w http.ResponseWriter, r *http.Request) { url.Path = path.Join("/notes/", filetree.NewPathFromURL(r.URL.Path).BaseHREF) http.Redirect(w, r, url.String(), http.StatusSeeOther) } + +func trimLines(s string) string { + buff := bytes.NewBuffer(nil) + for _, line := range strings.Split(s, "\n") { + fmt.Fprintln(buff, strings.TrimRight(line, "\n \r\t")) + } + fixed := string(buff.Bytes()) + return fixed[:len(fixed)-1] +} diff --git a/server/submit_test.go b/server/submit_test.go new file mode 100644 index 0000000..0e8a637 --- /dev/null +++ b/server/submit_test.go @@ -0,0 +1,36 @@ +package server + +import "testing" + +func TestTrimLines(t *testing.T) { + t.Run("no newline at end", func(t *testing.T) { + s := ` + hello + world` + s += " " + s += " \t" + got := trimLines(s) + want := ` + hello + world` + if got != want { + t.Fatalf("want %q, got %q", want, got) + } + }) + t.Run("noop", func(t *testing.T) { + s := `hi` + got := trimLines(s) + want := `hi` + if got != want { + t.Fatalf("want %q, got %q", want, got) + } + }) + t.Run("newline", func(t *testing.T) { + s := "hi\n" + got := trimLines(s) + want := "hi\n" + if got != want { + t.Fatalf("want %q, got %q", want, got) + } + }) +}