go - 如何在golang中使用mux和gorm发布body raw?
问题描述
我在使用 gorilla/mux 和 gorm 的方法发布时遇到问题,我想在 body raw 中请求,但是当我执行我的程序时我的代码是错误的,为什么我的代码错误?我仍然不明白使用 gorilla/mux 和 gorm 在正文中使用请求,如何在 golang 中使用 mux 和 gorm 制作帖子形式?
我的错误是:
package main
import (
"encoding/json"
"fmt"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mssql"
"log"
"net/http"
"strconv"
"time"
)
type SMSBlast struct {
SequenceID int `gorm:"column:SequenceID;PRIMARY_KEY"`
MobilePhone string `gorm:"column:MobilePhone"`
Output string `gorm:"column:Output"`
WillBeSentDate *time.Time `gorm:"column:WillBeSentDate"`
SentDate *time.Time `gorm:"column:SentDate"`
Status *string `gorm:"column:Status"`
DtmUpd time.Time `gorm:"column:DtmUpd"`
}
func (SMSBlast) TableName() string {
return "SMSBlast2"
}
func insertSMSBlast(w http.ResponseWriter, r *http.Request){
fmt.Println("New Insert Created")
db, err := gorm.Open("mssql", "sqlserver://sa:@localhost:1433?database=CONFINS")
if err != nil{
panic("failed to connect database")
}
defer db.Close()
vars := mux.Vars(r)
//sequenceid := vars["sequenceid"]
mobilephone := vars["mobilephone"]
output := vars["output"]
willbesentdate := vars["willbesentdate"]
sentdate := vars["sentdate"]
status := vars["status"]
var smsblats SMSBlast
json.NewDecoder(r.Body).Decode(&smsblats)
prindata := db.Debug().Raw("EXEC SMSBlast2Procedure ?, ?, ?, ? , ?", mobilephone, output, willbesentdate, sentdate, status).Scan(smsblats)
fmt.Println(prindata)
json.NewEncoder(w).Encode(&smsblats)
}
func handleRequests(){
myRouter := mux.NewRouter().StrictSlash(true)
myRouter.HandleFunc("/smsblaststestInsert", insertSMSBlast).Methods("POST")
log.Fatal(http.ListenAndServe(":8080",myRouter))
}
func main(){
fmt.Println("SMSBLASTS ORM")
handleRequests()
}
解决方案
这里没有太多数据可以输出,但您似乎访问了错误的值并获得了空白字符串作为回报。
vars := mux.Vars(r)
mobilephone := vars["mobilephone"]
output := vars["output"]
willbesentdate := vars["willbesentdate"]
sentdate := vars["sentdate"]
status := vars["status"]
Gorilla 会期望这些都是请求路径中存在的值 ( /{mobilephone}/{output}/{willbesentdate}
。我怀疑情况并非如此,因为您还将请求正文读入了结构。
删除该部分并且不要使用这些值,使用加载到结构中的值。
推荐阅读
- sql - 如何从重复的行号中找到最小值?
- c# - Unity - EditorGUILayout 在可序列化字段中显示隐藏元素
- mysql - 如何比较同一个表的行并将另一个表的权重应用于每一列
- highcharts - 在highchart中添加点后获取ID
- laravel - laravel socialite 不能在实时服务器上工作,只能在本地机器上工作
- windows - Windows 中是否有“command -v”的等价物?
- react-native - cli.js require('@reat-native-community/cli') 找不到模块
- r - R - 图形交叉线
- python - 逻辑回归残差图/分布
- scala - 从不使用案例类的元组序列中创建具有数据框的数据集