使用 Mux 在 Golang 中进行批量发布
来源:stackoverflow
时间:2024-02-17 14:15:23 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学习网公众号。
声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
-
502 收藏
-
502 收藏
-
501 收藏
-
501 收藏
-
501 收藏
最新阅读
更多>
-
139 收藏
-
204 收藏
-
325 收藏
-
478 收藏
-
486 收藏
-
439 收藏
-
357 收藏
-
352 收藏
-
101 收藏
-
440 收藏
-
212 收藏
-
143 收藏
课程推荐
更多>
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习