Created
March 4, 2012 07:23
-
-
Save kylelemons/1971123 to your computer and use it in GitHub Desktop.
How to safely parse wiki text and insert links with html/template.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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