猿问

Golang 通过 Mux 批量发布

您好,我是 Golang 的新手,我正在尝试使用 Mux 进行批量 POST。我希望能够发布多个“生产”项目,而不仅仅是一个。


在这里,我正在定义什么是农产品


// 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

这是我当前的 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 //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)

    }

}

它在 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

}

我希望能够一次发布多个农产品项目,例如....


[

    {

        "name": "Green Pepper",

        "code": "YRT6-72AS-K736-L4AR",

        "unit_price": 0.79

    },

    {

        "name": "Gala Apple",

        "code": "TQ4C-VV6T-75ZX-1RMR",

        "unit_price": 3.59

    },

]

谢谢


喵喔喔
浏览 173回答 1
1回答

扬帆大鱼

显然有很多方法可以解决,这里有一个package mainimport (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "log"&nbsp; &nbsp; "math"&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "regexp"&nbsp; &nbsp; "github.com/gorilla/mux")type Produce struct {&nbsp; &nbsp; Name&nbsp; &nbsp; &nbsp; &nbsp;string&nbsp; `json:"name"`&nbsp; &nbsp; Code&nbsp; &nbsp; &nbsp; &nbsp;string&nbsp; `json:"code"`&nbsp; &nbsp; Unit_Price float64 `json:"unit_price"`}type ProduceList []Produce// global var where all produce is kept,// not persistentvar produce ProduceListfunc addProduce(w http.ResponseWriter, r *http.Request) {&nbsp; &nbsp; // we accept a json and decode it into a slice of structs&nbsp; &nbsp; var newProduceItems ProduceList&nbsp; &nbsp; err := json.NewDecoder(r.Body).Decode(&newProduceItems)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; var tempItems ProduceList&nbsp; &nbsp; re := regexp.MustCompile("^[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}$")&nbsp; &nbsp; // iterate over each element in the posted json and validate&nbsp; &nbsp; // when validated, add to the temporary accumulator&nbsp; &nbsp; // if not validated, error out and stop&nbsp; &nbsp; for idx, produceItem := range newProduceItems {&nbsp; &nbsp; &nbsp; &nbsp; if !re.MatchString(produceItem.Code) || len(produceItem.Name) <= 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; errMsg := fmt.Sprintf("Item %d: Incorrect produce code sequence or product name. Example code sequence: A12T-4GH7-QPL9-3N4M", idx)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; http.Error(w, errMsg, http.StatusBadRequest)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; produceItem.Unit_Price = math.Round(produceItem.Unit_Price*100) / 100 //rounds to the nearest cent&nbsp; &nbsp; &nbsp; &nbsp; tempItems = append(tempItems, produceItem)&nbsp; &nbsp; }&nbsp; &nbsp; // after validation, append new items to the global accumulator and respond back with added items&nbsp; &nbsp; produce = append(produce, tempItems...)&nbsp; &nbsp; w.Header().Set("Content-Type", "application/json")&nbsp; &nbsp; if err = json.NewEncoder(w).Encode(newProduceItems); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Panic(err)&nbsp; &nbsp; }}func main() {&nbsp; &nbsp; router := mux.NewRouter()&nbsp; &nbsp; router.HandleFunc("/produce", addProduce).Methods("POST")&nbsp; &nbsp; log.Fatal(http.ListenAndServe(":8000", router))}
随时随地看视频慕课网APP

相关分类

Go
我要回答