我的功能有问题
func (driver *DBClient) GetUsersByFirstName(w http.ResponseWriter, r *http.Request) {
var users []models.User
name := r.FormValue("first_name")
// Handle response details
var query = "select * from \"user\" where data->>'first_name'=?"
driver.db.Raw(query, name).Scan(&users)
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
//responseMap := map[string]interface{}{"url": ""}
respJSON, _ := json.Marshal(users)
w.Write(respJSON)
}
当我使用 POST 时
curl -X POST \
http://localhost:8000/v1/user \
-H 'cache-control: no-cache' \
-H 'content-type: application/json' \
-d '{
"username": "tsarcayan",
"email_address": "rsarnayan@gmail.com",
"first_name": "tigran",
"last_name": "tanayan"
}'
输出
{"id":4}
但是当我尝试获取用户 tigran 的 first_name 时
curl -X GET http://localhost:8000/v1/user/"tigran"
我得到了
{"user":{"ID":0,"CreatedAt":"0001-01-01T00:00:00Z","UpdatedAt":"0001-01-01T00:00:00Z","DeletedAt":null,"Orders":null},"data":null}`
如何解决这个问题?
我的 handle
r.HandleFunc("/v1/user", dbclient.GetUsersByFirstName).Methods("GET")
最佳答案
可能您应该使用 url 作为 http://localhost:8000/v1/user?first_name=tigran
并获取该参数作为 req.URL.Query()["first_name"][0]
但不要忘记用户输入检查
关于go - 为什么 curl 为我的用户提供了错误的 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55608470/