Page MenuHomeMusing Studio

No OneTemporary

diff --git a/posts/parse.go b/posts/parse.go
new file mode 100644
index 0000000..85d0c4d
--- /dev/null
+++ b/posts/parse.go
@@ -0,0 +1,19 @@
+package posts
+
+import (
+ "strings"
+)
+
+func ExtractTitle(content string) (title string, body string) {
+ if hashIndex := strings.Index(content, "# "); hashIndex == 0 {
+ eol := strings.IndexRune(content, '\n')
+ // First line should start with # and end with \n
+ if eol != -1 {
+ body = strings.TrimLeft(content[eol:], " \t\n\r")
+ title = content[len("# "):eol]
+ return
+ }
+ }
+ body = content
+ return
+}
diff --git a/posts/parse_test.go b/posts/parse_test.go
new file mode 100644
index 0000000..71245fe
--- /dev/null
+++ b/posts/parse_test.go
@@ -0,0 +1,35 @@
+package posts
+
+import (
+ "testing"
+)
+
+type titleTest struct {
+ in, title, body string
+}
+
+func TestExtractTitle(t *testing.T) {
+ tests := []titleTest{
+ {`# Hello World
+This is my post`, "Hello World", "This is my post"},
+ {"No title", "", "No title"},
+ {`Not explicit title
+
+It's not explicit.
+Yep.`, "", `Not explicit title
+
+It's not explicit.
+Yep.`},
+ {"# Only a title", "", "# Only a title"},
+ }
+
+ for _, test := range tests {
+ title, body := ExtractTitle(test.in)
+ if title != test.title {
+ t.Fatalf("Wanted title '%s', got '%s'", test.title, title)
+ }
+ if body != test.body {
+ t.Fatalf("Wanted body '%s', got '%s'", test.body, body)
+ }
+ }
+}

File Metadata

Mime Type
text/x-diff
Expires
Mon, Jan 20, 3:18 AM (1 d, 17 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3137579

Event Timeline