douwen7516 2017-08-10 13:00
浏览 69
已采纳

使用Go(Golang)清除先前的请求RESTFul吗?

I've created a RESTFul API via golang. The Issue is that when I send a /product request I will be given the result in json and when I repeat this request the result will append prevoius. I want to clear the REST data buffer and whenever I send a request, API send me fresh data, not with prevoius. What should I do?

Route Handler

func main() {
    router := mux.NewRouter()

    router.HandleFunc("/product", GetProductInfo).Methods("GET")

    log.Printf("Listenning on Port %s ...
", PORT)
    log.Fatal(http.ListenAndServe(PORT, router))
}

Request Handler

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)
}
  • 写回答

1条回答 默认 最新

  • doyhq66282 2017-08-10 13:04
    关注

    You are declaring this as a global variable in your package:

    var product_out []ProductOut
    

    That way, the slice is just created once, and you are sharing it between requests.

    If you want to declare a new slice for each request, you should move that line inside your GetProductInfo function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog