您可以执行以下操作:


var cols []string

var rows [][]interface{}


for key, _ := range result[0] {

    cols = append(cols, key)

}


for _, res := range result {

    vals := make([]interface{}, len(cols))

    for i, col := range cols {

        vals[i] = res[col]

    }

    rows = append(rows, vals)

}

data := struct {

    Title   string

    Columns []string

    Rows    [][]interface{}

}{

    Title:   "My page",

    Columns: cols,

    Rows:    rows,

}

并且需要相应地修改 HTML:


<table>

    <tr>

    {{range .Columns}}<th>{{ . }}</th>{{else}}<div><strong>no rows</strong></div>{{end}}

    </tr>

    {{- range .Rows}}

    <tr>

    {{range .}}<td>{{ . }}</td>{{end}}

    </tr>

    {{- end}}

</table>

https://go.dev/play/p/MPJOMlfQ488


result[0][]stringsortsql.Rows.Columns