亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Golang 通過 Mux 批量發布

Golang 通過 Mux 批量發布

Go
喵喔喔 2022-10-10 16:08:22
您好,我是 Golang 的新手,我正在嘗試使用 Mux 進行批量 POST。我希望能夠發布多個“生產”項目,而不僅僅是一個。在這里,我正在定義什么是農產品// Define the produce structuretype Produce struct {    Name string `json:"name"`    Code string `json:"code"`    Unit_Price float64 `json:"unit_price"`}// Init produce var as a Produce slicevar 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    },]謝謝
查看完整描述

1 回答

?
揚帆大魚

TA貢獻1799條經驗 獲得超9個贊

顯然有很多方法可以解決,這里有一個


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

}


查看完整回答
反對 回復 2022-10-10
  • 1 回答
  • 0 關注
  • 165 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號