使用 Mux 在 Golang 中进行批量发布
时间:2024-02-17
浏览:500
作者:佚名
哈喽!今天心血来潮给大家带来了《使用 Mux 在 Golang 中进行批量发布》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!
问题内容
您好,我是 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))
}
这是一个 json 数据的示例,当我在 postman 中 post 到它时,它正在工作
{
"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
},
]
谢谢
正确答案
显然有很多方法可以解决这个问题,这里是一个
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))
}以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.28
热门专题
