【问题标题】:Golang Batch Post Via MuxGolang 通过 Mux 批量发布
【发布时间】:2021-12-10 12:45:54
【问题描述】:

您好,我是 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
    },
]

谢谢

【问题讨论】:

  • 您好像在问如何解析 JSON 数组? (见this example)。将var newProduceItem Produce 更改为var newProduceItems []Produce 将帮助您完成大部分工作。
  • 您需要同时支持[]ProduceProduce 还是只更新API 以采用[]Produce

标签: json api go post


【解决方案1】:

显然有很多方法可以解决,这里有一个

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))
}

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 2018-06-24
    • 2014-02-09
    • 2020-02-19
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    相关资源
    最近更新 更多