首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Golang批量投递通过Mux

Golang批量投递通过Mux
EN

Stack Overflow用户
提问于 2021-10-24 22:15:24
回答 1查看 47关注 0票数 1

你好,我是新来Golang的,我正在尝试用Mux做一个批量发布。我希望能够张贴多个“生产”项目,而不是只有一个。

在这里,我定义了什么是produce项

代码语言:javascript
复制
// 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

这是我目前的邮政编码

代码语言:javascript
复制
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()函数中调用,如下所示。

代码语言:javascript
复制
func main() {
    router := mux.NewRouter()
    router.HandleFunc("/produce", addProduce).Methods("POST")
    log.Fatal(http.ListenAndServe(":8000", router))
}

下面是一个JSON数据的示例,当我在Postman中对其进行POST操作时,该数据正在工作

代码语言:javascript
复制
{
    "name":"Peach",
    "code": "TTTT-44D4-A12T-1224",
    "unit_price": 5.3334
}

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

代码语言:javascript
复制
[
    {
        "name": "Green Pepper",
        "code": "YRT6-72AS-K736-L4AR",
        "unit_price": 0.79
    },
    {
        "name": "Gala Apple",
        "code": "TQ4C-VV6T-75ZX-1RMR",
        "unit_price": 3.59
    },
]

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-25 00:11:15

显然,有很多方法可以做到这一点,下面就是其中之一

代码语言:javascript
复制
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))
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69701166

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档