mark2web/helper/template_functions.go

68 lines
1.3 KiB
Go
Raw Normal View History

2019-02-27 15:58:10 +01:00
package helper
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/davecgh/go-spew/spew"
"github.com/flosch/pongo2"
)
2019-02-27 17:33:26 +01:00
// RequestFn will make a web request and returns map[string]interface form pongo2
func RequestFn(url *pongo2.Value, args ...*pongo2.Value) *pongo2.Value {
2019-02-27 15:58:10 +01:00
u := url.String()
fmt.Printf("request GET %s\n", u)
resp, err := http.Get(u)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
panic(err)
}
spew.Dump(string(body))
if resp.StatusCode >= 400 {
panic(resp.Status)
}
contentType := resp.Header.Get("Content-Type")
if strings.Contains(contentType, "json") {
} else {
panic("invalid content-type")
}
jsonMap := make(map[string]interface{})
err = json.Unmarshal(body, &jsonMap)
if err != nil {
panic(err)
}
return pongo2.AsValue(jsonMap)
}
2019-02-27 17:33:26 +01:00
// RenderFn renders a pongo2 template with additional context
func RenderFn(templateFilename, outDir, subCtxName, ctx *pongo2.Value) *pongo2.Value {
currentContext[subCtxName.String()] = ctx
result, err := RenderTemplate(templateFilename.String(), currentContext)
if err != nil {
panic(err)
}
result = FixAssetsPath(
result,
currentContext["CurrentPath"].(string),
)
spew.Dump(result)
return pongo2.AsValue(nil)
}