Created
April 27, 2018 03:05
-
-
Save phated/c272059787a75f789b3e68e5259411b6 to your computer and use it in GitHub Desktop.
Abusing funcMap and text/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 ( | |
"errors" | |
"io/ioutil" | |
"log" | |
"net/http" | |
"os" | |
"text/template" | |
) | |
func goGet(url string, out chan interface{}) interface{} { | |
// out := make(chan string) | |
go func() { | |
out <- get(url) | |
}() | |
return <-out | |
} | |
func get(urlStr string) string { | |
r, err := http.Get(urlStr) | |
if err != nil { | |
log.Fatal(err) | |
} | |
body, err2 := ioutil.ReadAll(r.Body) | |
r.Body.Close() | |
if err2 != nil { | |
log.Fatal(err) | |
} | |
return string(body) | |
} | |
type storage struct { | |
data interface{} | |
} | |
func keywordMake() string { | |
return "make" | |
} | |
func keywordChan(arg string) (*string, error) { | |
out := "makechan" | |
if arg == "make" { | |
return &out, nil | |
} | |
return nil, errors.New("invalid keyword") | |
} | |
func keywordString(arg string) (chan interface{}, error) { | |
if arg == "makechan" { | |
return make(chan interface{}), nil | |
} | |
return nil, errors.New("invalid keyword") | |
} | |
func betterHttp(str string) { | |
// First we create a FuncMap with which to register the function. | |
funcMap := template.FuncMap{ | |
"get": goGet, | |
"make": keywordMake, | |
"chan": keywordChan, | |
"string": keywordString, | |
} | |
// Create a template, add the function map, and parse the text. | |
tmpl, err := template.New("blah").Funcs(funcMap).Parse(str) | |
if err != nil { | |
log.Fatalf("parsing: %s", err) | |
} | |
// Run the template to verify the output. | |
err = tmpl.Funcs(funcMap).Execute(os.Stdout, storage{}) | |
if err != nil { | |
log.Fatalf("execution: %s", err) | |
} | |
} | |
func main() { | |
str := `{{get "https://api.github.com/users/phated/repos?per_page=1" (make | chan | string)}}` | |
betterHttp(str) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment