mark2web/helper/template_functions.go
Sebastian Frank 8f1345d4aa
All checks were successful
continuous-integration/drone/push Build is passing
fnRequest, pongo2-addons added
2019-02-27 15:58:10 +01:00

52 lines
884 B
Go

package helper
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"github.com/davecgh/go-spew/spew"
"github.com/flosch/pongo2"
)
// Request will make a web request and returns map[string]interface form pongo2
func Request(url *pongo2.Value, args ...*pongo2.Value) *pongo2.Value {
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)
}