我已经通过golang创建了一个RESTFul API。
问题是,当我发送/product
请求时,我将在json中获得结果,当我重复此请求时,结果将追加prevoius。
我想清除REST数据缓冲区,每当我发送请求时,API都会向我发送新数据,而不是prevoius。我该怎么办?
func main() {
router := mux.NewRouter()
router.HandleFunc("/product", GetProductInfo).Methods("GET")
log.Printf("Listenning on Port %s ...\n", PORT)
log.Fatal(http.ListenAndServe(PORT, router))
}
type ProductOut struct {
ID int `json:"id,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Price string `json:"price,omitempty"`
Location string `json:"location,omitempty"`
Created_at string `json:"created_at,omitempty"`
Images []string `json:"images,omitempty"`
}
var product_out []ProductOut
func GetProductInfo(w http.ResponseWriter, r *http.Request) {
db_select_products := db.SelectProducts() // Gets data from database
var out ProductOut
for _, ele := range db_select_products {
out.ID = contentGetFieldInteger(ele, "out_id") // A method for getting integer from struct field
out.Title = contentGetFieldString(ele, "out_title") // A method for getting string from struct field
out.Description = contentGetFieldString(ele, "out_description")
out.Price = contentGetFieldString(ele, "out_price")
out.Location = contentGetFieldString(ele, "out_location")
out.Created_at = contentGetFieldString(ele, "out_created_at")
db_select_image := db.SelectImages(out.ID) // Gets another data from database
for _, imele := range db_select_image {
out.Images = append(out.Images, imageGetFieldString(imele, "out_path"))
fmt.Println(out.Images)
}
product_out = append(product_out, out)
out.Images = nil
}
json.NewEncoder(w).Encode(product_out)
}
答案 0 :(得分:3)
您将此声明为程序包中的全局变量:
var product_out []ProductOut
这样,切片只创建一次,然后在请求之间共享。
如果要为每个请求声明一个新切片,则应将该行移到GetProductInfo
函数中。