Example #1
0
func (g *Generator) generateIndexHTML(
	htmlFile string,
	api *design.APIDefinition,
	exampleAction *design.ActionDefinition,
	funcs template.FuncMap,
) error {
	file, err := os.Create(htmlFile)
	if err != nil {
		return err
	}
	defer file.Close()
	g.genfiles = append(g.genfiles, htmlFile)

	htmlTmpl := template.Must(template.New("exampleHTML").Funcs(funcs).Parse(exampleT))

	argNames := params(exampleAction)
	var args string
	if len(argNames) > 0 {
		query := exampleAction.QueryParams.Type.ToObject()
		argValues := make([]string, len(argNames))
		for i, n := range argNames {
			q := query[n].Type.ToArray().ElemType
			// below works because we deal with simple types in query strings
			argValues[i] = fmt.Sprintf("%v", api.Example(q.Type))
		}
		args = strings.Join(argValues, ", ")
	}
	examplePath := exampleAction.Routes[0].FullPath()
	pathParams := exampleAction.Routes[0].Params()
	if len(pathParams) > 0 {
		pathVars := exampleAction.AllParams().Type.ToObject()
		pathValues := make([]interface{}, len(pathParams))
		for i, n := range pathParams {
			pathValues[i] = api.Example(pathVars[n].Type)
		}
		format := design.WildcardRegex.ReplaceAllLiteralString(examplePath, "/%v")
		examplePath = fmt.Sprintf(format, pathValues...)
	}
	if len(argNames) > 0 {
		args = ", " + args
	}
	exampleFunc := fmt.Sprintf(
		`%s%s ("%s"%s)`,
		exampleAction.Name,
		strings.Title(exampleAction.Parent.Name),
		examplePath,
		args,
	)
	data := map[string]interface{}{
		"API":         api,
		"ExampleFunc": exampleFunc,
	}
	return htmlTmpl.Execute(file, data)
}