1
I am trying to filter my records based on a "Name parameter"
I did this Handler Function:
func GetFuncionaries(w http.ResponseWriter, r *http.Request) {
var f model.Funcionary
var t util.App
var d db.DB
err := d.Connection()
db := d.DB
defer db.Close()
Id, _ := strconv.Atoi(r.FormValue("Id"))
Name:= r.FormValue("Name")
f.Id = int64(Id)
f.Name = Name
funcionaries, err := f.GetFuncionaries(db)
if err != nil {
log.Printf("[handler/GetFuncionaries- Error: %s", err.Error())
t.ResponseWithError(w, http.StatusInternalServerError, err.Error(), "")
}
return
}
t.ResponseWithJSON(w, http.StatusOK, funcionaries, 0, 0)
}
And that’s my role model:
func (f *Funcionary) GetFuncionaries(db *sql.DB) ([]Funcionary, error) {
var values []interface{}
var where []string
if f.Name != "" {
where = append(where, "Name= ?")
values = append(values, f.Name)
}
rows, err := db.Query(`SELECT Id, Data, Role, Name
FROM funcionaries
WHERE 1=1 `+strings.Join(where, " AND "), values...)
if err != nil {
return nil, err
}
funcionaries:= []Funcionary{}
defer rows.Close()
for rows.Next() {
var funcionary Funcionary
if err = rows.Scan(&funcionario.Id, &funcionario.Name, &Others...); err != nil {
return nil, err
}
funcionaries = append(funcionaries, funcionary)
}
return funcionaries, nil
}
But when I make a request at Postman:
http://localhost:8000/api/funcies? Name=a
I get:
You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near 'Name= ? ' at line 3",
I’m forgetting one thing?
You have already run the query "at hand" and is functional?
– Caio Augusto Papai