如何查询多个行并解析为json?

I have this code:

func GetAll(c *gin.Context) {

var veiculos model.Veiculo

rows, err := db.Query("SELECT * FROM vei_veiculo")
if err != nil {
    fmt.Println("[GetAll] erro ao abrir o query db inteiro")
}
defer rows.Close()
for rows.Next() {
    err := rows.Scan(&veiculos)
    if err != nil {
        fmt.Println("[GetAll] erro ao scanear uma linha'")
    }
}
fmt.Println(veiculos)}

My struct name is at model.Veiculo and I want to print it all once. It seems there is an error on scan the query rows. What did I do wrong?

Assuming you are using database/sql, the function signature is func (rs *Rows) Scan(dest ...interface{}) error.

You need to be doing scanning into each member of the struct, something more like:

err := rows.Scan(&veiculos.ID, &veiculos.Name, &veiculos.Description)

To scan each row to its own struct, I recommend an approach like so:

package main

import (
    "database/sql"
    "fmt"
    "log"

    _ "github.com/go-sql-driver/mysql"
)

type Person struct {
    FirstName string
    LastName  string
    Email     string
}

func main() {
    db, err := sql.Open("mysql", "dsn...")
    if err != nil {
        log.Fatalln(err)
    }
    defer db.Close()

    people := []Person{}

    rows, err := db.Query("SELECT * FROM people")
    if err != nil {
        log.Fatalln(err)
    }

    for rows.Next() {
        person := Person{}
        if err := rows.Scan(&person.FirstName, &person.LastName, &person.Email); err != nil {
            log.Fatalln(err)
        }
        people = append(people, person)
    }

    fmt.Printf("%+v
", people)
}

Alternatively, the library https://github.com/jmoiron/sqlx exists as one of the solutions to marshaling SQL query data to structs. I personally prefer this method, as it behaves more like an Unmarshal function:

package main

import (
    "fmt"
    "log"

    _ "github.com/go-sql-driver/mysql"
    "github.com/jmoiron/sqlx"
)

type Person struct {
    FirstName string `db:"first_name"`
    LastName  string `db:"last_name"`
    Email     string `db:"email"`
}

func main() {
    db, err := sqlx.Connect("mysql", "dsn...")
    if err != nil {
        log.Fatalln(err)
    }

    people := []Person{}

    if err := db.Select(&people, "SELECT * FROM people"); err != nil {
        log.Fataln(err)
    }

    fmt.Printf("%+v
", people)
}

Following either of these approaches allows you to easily use the json.Marshal method with the people variable, and viola!

Good luck!