我正在嘗試使用 Golang 和 Gin 作為我的路由器和 SQLC for SQL code gen 進行全文搜索。無論我將查詢系結為 URI 還是查詢,我都會得到一個空串列。請幫忙。
type searchProductRequest struct {
q string `form:"q" binding:"required"`
PageSize int32 `form:"page_size" binding:"required,min=1,max=10"`
}
func (server *Server) searchProduct(ctx *gin.Context) {
var req searchProductRequest
if err := ctx.ShouldBindQuery(&req); err != nil {
ctx.JSON(http.StatusBadRequest, errorResponse(err))
return
}
arg := db.SearchProductParams{
Limit: req.PageSize,
SearchQuery: req.q,
}
product, err := server.store.SearchProduct(ctx, arg)
if err != nil {
if err == sql.ErrNoRows {
ctx.JSON(http.StatusNotFound, errorResponse(err))
return
}
ctx.JSON(http.StatusInternalServerError, errorResponse(err))
return
}
ctx.JSON(http.StatusOK, product)
}
下面是查詢功能:
const searchProduct = `-- name: SearchProduct :many
SELECT id, name, owner, price, description, imgs_url, imgs_name, created_at, tsv
FROM products
WHERE textsearchable_index_col @@ to_tsquery($2)
ORDER BY created_at DESC
LIMIT $1
`
type SearchProductParams struct {
Limit int32 `json:"limit"`
SearchQuery string `json:"search_query"`
}
func (q *Queries) SearchProduct(ctx context.Context, arg SearchProductParams) ([]Product, error) {
rows, err := q.db.QueryContext(ctx, searchProduct, arg.Limit, arg.SearchQuery)
if err != nil {
return nil, err
}
defer rows.Close()
items := []Product{}
for rows.Next() {
var i Product
if err := rows.Scan(
&i.ID,
&i.Name,
&i.Owner,
&i.Price,
&i.Description,
pq.Array(&i.ImgsUrl),
pq.Array(&i.ImgsName),
&i.CreatedAt,
&i.Tsv,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Close(); err != nil {
return nil, err
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
對我的資料庫運行 SQL 原始查詢,我得到帶有我發送的查詢的產品。下面是sql查詢:
-- name: SearchProduct :many
SELECT *
FROM products
WHERE textsearchable_index_col @@ to_tsquery(sqlc.arg(search_query))
ORDER BY created_at DESC
LIMIT $1;
我試圖在郵遞員中將請求作為 URI 和表單引數傳遞,但是這兩種方法仍然回傳 200 狀態和一個空串列。請問這個功能有什么問題?我究竟做錯了什么?這是我學習 GO 的第三個月。
uj5u.com熱心網友回復:
q,因為它以小寫字母開頭,所以是unexported,這意味著在宣告它的包之外的任何代碼都無法訪問它。包括反射,它由您傳遞到的系結方法使用req。換句話說,更改q為Q。
這是關于此事的官方語言規范:https ://go.dev/ref/spec#Exported_identifiers
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/513871.html
標籤:去去金酒sqlc
上一篇:如何制作從介面轉換的可尋址吸氣劑
