清除之前的请求RESTful与Go(Golang)?

huangapple go评论85阅读模式
英文:

Clearing out Previous Request RESTFul with Go(Golang)?

问题

我已经通过golang创建了一个RESTful API。问题是,当我发送一个/product请求时,我会得到一个json格式的结果,当我重复发送这个请求时,结果会追加到之前的结果中。我想要清除REST数据缓冲区,每当我发送一个请求时,API都会给我发送新鲜的数据,而不是之前的数据。我应该怎么做?

路由处理程序:

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() // 从数据库获取数据

    var out ProductOut

    for _, ele := range db_select_products {
        out.ID = contentGetFieldInteger(ele, "out_id") // 从结构字段中获取整数的方法
        out.Title = contentGetFieldString(ele, "out_title") // 从结构字段中获取字符串的方法
        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) // 从数据库获取另一组数据

        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)
}
英文:

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 ...\n", 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

得分: 3

你可以在你的包中将其声明为全局变量:

var product_out []ProductOut

这样,切片只会被创建一次,并在请求之间共享。

如果你想为每个请求声明一个新的切片,你应该将那行代码移到你的 GetProductInfo 函数内部。

英文:

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.

huangapple
  • 本文由 发表于 2017年8月10日 21:00:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/45614430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定