英文:
Golang Batch Post Via Mux
问题
你好,我是你的中文翻译助手。以下是你要翻译的内容:
你好,我是Golang的新手,我正在尝试使用Mux进行批量POST。我希望能够一次性POST多个"produce"项目,而不仅仅是一个。
这里是我定义的"produce"项目的结构:
// 定义produce结构
type Produce struct {
Name       string  json:"name"
Code       string  json:"code"
Unit_Price float64 json:"unit_price"
}
// 将produce变量初始化为Produce切片
var produce []Produce
这是我当前的POST代码:
func addProduce(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    var newProduceItem Produce
    _ = json.NewDecoder(r.Body).Decode(&newProduceItem)
    re := regexp.MustCompile("^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}$")
    if re.MatchString(newProduceItem.Code) == true && len(newProduceItem.Name) > 0 {
        newProduceItem.Unit_Price = math.Round(newProduceItem.Unit_Price*100) / 100 // 四舍五入到最近的分
        produce = append(produce, newProduceItem)
        json.NewEncoder(w).Encode(newProduceItem)
    } else {
        http.Error(w, fmt.Sprintf("Incorrect produce code sequence or product name. Example code sequence: A12T-4GH7-QPL9-3N4M"), http.StatusBadRequest)
    }
}
在main()函数中调用它,如下所示:
func main() {
    router := mux.NewRouter()
    router.HandleFunc("/produce", addProduce).Methods("POST")
    log.Fatal(http.ListenAndServe(":8000", router))
}
这是一个在Postman中POST时有效的JSON数据示例:
{
"name": "Peach",
"code": "TTTT-44D4-A12T-1224",
"unit_price": 5.3334
}
我希望能够一次性POST多个produce项目,例如:
[
{
"name": "Green Pepper",
"code": "YRT6-72AS-K736-L4AR",
"unit_price": 0.79
},
{
"name": "Gala Apple",
"code": "TQ4C-VV6T-75ZX-1RMR",
"unit_price": 3.59
}
]
谢谢!
英文:
Hello I'm new to Golang and I'm attempting to do a batch POST with Mux. I want to be able to POST multiple "produce" items instead of just a single one.
Here I'm defining what a produce item is
// Define the produce structure
type Produce struct {
	Name string `json:"name"`
	Code string `json:"code"`
	Unit_Price float64 `json:"unit_price"`
}
// Init produce var as a Produce slice
var produce []Produce
Here is my current POST code
func addProduce(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	var newProduceItem Produce
	_ = json.NewDecoder(r.Body).Decode(&newProduceItem)
	re := regexp.MustCompile("^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}$")
	if re.MatchString(newProduceItem.Code) == true && len(newProduceItem.Name) > 0 {
		newProduceItem.Unit_Price = math.Round(newProduceItem.Unit_Price*100) / 100 //rounds to the nearest cent
		produce = append(produce, newProduceItem)
		json.NewEncoder(w).Encode(newProduceItem)
	} else {
		http.Error(w, fmt.Sprintf("Incorrect produce code sequence or product name. Example code sequence: A12T-4GH7-QPL9-3N4M"), http.StatusBadRequest)
	}
}
It is called in the main() function as seen here.
func main() {
	router := mux.NewRouter()
	router.HandleFunc("/produce", addProduce).Methods("POST")
	log.Fatal(http.ListenAndServe(":8000", router))
}
Here an example of JSON data that is working when I POST to it in Postman
{
    "name":"Peach",
    "code": "TTTT-44D4-A12T-1224",
    "unit_price": 5.3334
}
I want to be able to post multiple produce items at once such as....
[
    {
        "name": "Green Pepper",
        "code": "YRT6-72AS-K736-L4AR",
        "unit_price": 0.79
    },
    {
        "name": "Gala Apple",
        "code": "TQ4C-VV6T-75ZX-1RMR",
        "unit_price": 3.59
    },
]
Thank you
答案1
得分: 1
这是一个示例代码,它使用Go语言编写了一个简单的HTTP服务器。代码中定义了一个名为Produce的结构体,表示产品的属性,以及一个名为ProduceList的切片,表示多个产品。addProduce函数用于处理POST请求,将接收到的JSON数据解码为ProduceList类型,并进行验证。验证通过后,将产品添加到全局变量produce中,并返回添加的产品信息。main函数创建了一个路由器,并将addProduce函数与路径"/produce"绑定,然后启动HTTP服务器监听端口8000。
请注意,这只是一个示例代码,具体的业务逻辑和功能可能需要根据实际需求进行修改和完善。
英文:
There are clearly many ways to go about it, here is one
package main
import (
	"encoding/json"
	"fmt"
	"log"
	"math"
	"net/http"
	"regexp"
	"github.com/gorilla/mux"
)
type Produce struct {
	Name       string  `json:"name"`
	Code       string  `json:"code"`
	Unit_Price float64 `json:"unit_price"`
}
type ProduceList []Produce
// global var where all produce is kept,
// not persistent
var produce ProduceList
func addProduce(w http.ResponseWriter, r *http.Request) {
	// we accept a json and decode it into a slice of structs
	var newProduceItems ProduceList
	err := json.NewDecoder(r.Body).Decode(&newProduceItems)
	if err != nil {
		log.Panic(err)
	}
	var tempItems ProduceList
	re := regexp.MustCompile("^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}$")
	// iterate over each element in the posted json and validate
	// when validated, add to the temporary accumulator
	// if not validated, error out and stop
	for idx, produceItem := range newProduceItems {
		if !re.MatchString(produceItem.Code) || len(produceItem.Name) <= 0 {
			errMsg := fmt.Sprintf("Item %d: Incorrect produce code sequence or product name. Example code sequence: A12T-4GH7-QPL9-3N4M", idx)
			http.Error(w, errMsg, http.StatusBadRequest)
			return
		}
		produceItem.Unit_Price = math.Round(produceItem.Unit_Price*100) / 100 //rounds to the nearest cent
		tempItems = append(tempItems, produceItem)
	}
	// after validation, append new items to the global accumulator and respond back with added items
	produce = append(produce, tempItems...)
	w.Header().Set("Content-Type", "application/json")
	if err = json.NewEncoder(w).Encode(newProduceItems); err != nil {
		log.Panic(err)
	}
}
func main() {
	router := mux.NewRouter()
	router.HandleFunc("/produce", addProduce).Methods("POST")
	log.Fatal(http.ListenAndServe(":8000", router))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论