我对Go还很陌生,正在尝试确定是否有一种更简洁的方法来完成从前端(JS)到我的API的JSON数据的规范化。为了确保在从结构体(model.Expense)创建变量时使用正确的类型,我将有效负载转储到map中,然后进行规范化,并保存回结构体。如果有人能教我一个更好的方法来处理这件事,我将不胜感激!先谢谢你了!
模型。费用结构:
type Expense struct {
Id primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
Name string `json:"name"`
Frequency int `json:"frequency"`
StartDate *time.Time `json:"startDate"`
EndDate *time.Time `json:"endDate,omitempty"`
Cost primitive.Decimal128 `json:"cost"`
Paid []string `json:"paid,omitempty"`
}
所述控制器:
func InsertOneExpense(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Allow-Control-Allow-Methods", "POST")
var expense map[string]interface{}
json.NewDecoder(r.Body).Decode(&expense)
var expenseName string
if name, ok := expense["name"]; ok {
expenseName = fmt.Sprintf("%v", name)
} else {
json.NewEncoder(w).Encode("missing required name")
}
var expenseFrequency int
if frequency, ok := expense["frequency"]; ok {
expenseFrequency = int(frequency.(float64))
} else {
expenseFrequency = 1
}
// Handle startDate normalization
var expenseStartDate *time.Time
if startDate, ok := expense["startDate"]; ok {
startDateString := fmt.Sprintf("%v", startDate)
startDateParsed, err := time.Parse("2006-01-02 15:04:05", startDateString)
if err != nil {
log.Fatal(err)
}
expenseStartDate = &startDateParsed
} else {
json.NewEncoder(w).Encode("missing required startDate")
}
// Handle endDate normalization
var expenseEndDate *time.Time
if endDate, ok := expense["endDate"]; ok {
endDateString := fmt.Sprintf("%v", endDate)
endDateParsed, err := time.Parse("2006-01-02 15:04:05", endDateString)
if err != nil {
log.Fatal(err)
}
expenseEndDate = &endDateParsed
} else {
expenseEndDate = nil
}
// Handle cost normaliztion
var expenseCost primitive.Decimal128
if cost, ok := expense["cost"]; ok {
costString := fmt.Sprintf("%v", cost)
costPrimitive, err := primitive.ParseDecimal128(costString)
if err != nil {
log.Fatal(err)
}
expenseCost = costPrimitive
} else {
json.NewEncoder(w).Encode("missing required cost")
return
}
normalizedExpense := model.Expense{
Name: expenseName,
Frequency: expenseFrequency,
StartDate: expenseStartDate,
EndDate: expenseEndDate,
Cost: expenseCost,
}
// Do more things with the struct var...
}
1条答案
按热度按时间2q5ifsrm1#
您可以定义
json.UnmarshalJSON
接口,然后根据需要手动验证数据。试试这样的方法:输出:
{MoneyOwed:123.12}
Playground链接:https://go.dev/play/p/glStUbwpCCX