Skip to content

Instantly share code, notes, and snippets.

@kylelemons
Created March 4, 2012 07:23
Show Gist options
  • Select an option

  • Save kylelemons/1971123 to your computer and use it in GitHub Desktop.

Select an option

Save kylelemons/1971123 to your computer and use it in GitHub Desktop.
How to safely parse wiki text and insert links with html/template.
package main
import (
"bytes"
"fmt"
"html/template"
"log"
"regexp"
)
func main() {
// I/O
input := "The MethodSet of the interface is known & checked (see InterfaceSatisfaction) at compile time."
output := new(bytes.Buffer)
// Template
tpl, err := template.New("wiki").Parse(`
{{define "link"}}<a href="{{.URI}}">{{.Link}}</a>{{end}}
{{define "text"}}{{.}}{{end}}
`)
if err != nil {
log.Fatalf("parse: %s", err)
}
// Regexp
wikiword, err := regexp.Compile(`([[:upper:]][[:lower:]]+){2,}`)
if err != nil {
log.Fatalf("compile: %s", err)
}
idx := wikiword.FindAllStringSubmatchIndex(input, -1)
// Split repeatedly and write
start := 0
for _, idx := range idx {
link, end := idx[0], idx[1]
tpl.ExecuteTemplate(output, "text", input[start:link])
tpl.ExecuteTemplate(output, "link", map[string]string{
"URI": "/wiki/" + input[link:end],
"Link": input[link:end],
})
start = end
}
tpl.ExecuteTemplate(output, "text", input[start:])
fmt.Println(output)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment