我的功能有问题
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的名字
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}`
该如何解决?
我的handlefunc
r.HandleFunc("/v1/user", dbclient.GetUsersByFirstName).Methods("GET")
答案 0 :(得分:1)
可能您应该将url用作http://localhost:8000/v1/user?first_name=tigran
,并将该参数用作req.URL.Query()["first_name"][0]
,但不要忘记用户输入检查