我的函数收到一个http请求,并将json字符串作为http响应发回。 这是我的代码:
func homePage(res http.ResponseWriter, req *http.Request) {
type Resp struct {
Result []map[string]interface{} `json:"result,omitempty"`
Status string `json:"status"`
}
type Inputs struct {
ShopID string `json:"ShopID"`
DeviceID string `json:"DeviceID"`
EmpID string `json:"EmpID"`
Token string `json:"Token"`
Version string `json:"Version"`
}
var Response Resp
Response.Status = "failed"
db, err := sql.Open("mysql", "root:password@tcp(127.0.0.1:3306)/b2b")
if err != nil {
panic(err.Error())
}
defer db.Close()
rnd := render.New()
b, err := ioutil.ReadAll(req.Body)
defer req.Body.Close()
if err != nil {
panic(err.Error())
}
// Unmarshal the request body
var msg Inputs
err = json.Unmarshal(b, &msg)
if err != nil {
panic(err.Error())
}
bookingrows, bookingerr := db.Query("SELECT DISTINCT b2b_booking_id,b2b_check_in_report,b2b_vehicle_at_garage,b2b_service_under_progress,b2b_vehicle_ready,b2b_vehicle_delivered FROM b2b_booking_tbl WHERE b2b_flag=0 and b2b_shop_id=?", msg.ShopID)
if bookingerr != nil {
panic(bookingerr.Error())
} else {
Result := make(map[string]interface{})
for bookingrows.Next() {
var bookingid, checkinreported, vehicleingarage, serviceinprogress, vehicleready, vehicledelivered string
err = bookingrows.Scan(&bookingid, &checkinreported, &vehicleingarage, &serviceinprogress, &vehicleready, &vehicledelivered)
type Output struct {
checkins int `json:"checkins"`
inprogress int `json:"inprogress"`
ready int `json:"ready"`
completed int `json:"completed"`
}
var output Output
if err != nil {
panic(err.Error())
Response.Status = "failed"
}
if vehicledelivered == "1" {
output.completed = output.completed + 1
}
if vehicledelivered == "0" && vehicleready == "1" {
output.ready = output.ready + 1
}
if vehicledelivered == "0" && vehicleready == "0" && serviceinprogress == "1" {
output.inprogress = output.inprogress + 1
}
if vehicledelivered == "0" && vehicleready == "0" && serviceinprogress == "0" && (checkinreported == "1" || vehicleingarage == "1") {
output.checkins = output.checkins + 1
}
values := make([]string, 4)
val := reflect.ValueOf(output)
for i := range values {
//Result[usercolumns[i]] = fmt.Sprintf("%s", v)
Result[val.Type().Field(i).Tag.Get("json")] = fmt.Sprintf("%v", i)
}
}
Response.Result = append(Response.Result, Result)
Response.Status = "success"
}
res.Header().Set("Content-Type", "application/json")
rnd.JSON(res, http.StatusOK, Response)
}
当输入值正确且Db中存在相应的行时,我得到所需的输出。但是当输入错误或查询失败时,我应该只返回状态为"失败"但我的输出包含结果[],这是空的。
{
"result": [
{}
],
"status": "success"
}
我尝试检查Result == nil并仅将数组添加为true。但这对我没有帮助。可能是因为结构不是nill。 我需要一些帮助来找到问题并解决它。
答案 0 :(得分:2)
尝试在将if (len(Result) != 0) {
Response.Result = append(Response.Result, Result)
}
数组附加到输出
像这样的东西
Result := make(map[string]interface{})
也许你还需要在if条件中将这个{{1}}写在append语句之前