首页 > 解决方案 > 如何在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()
    }

标签: gogo-gormmux

解决方案


这里没有太多数据可以输出,但您似乎访问了错误的值并获得了空白字符串作为回报。

    vars := mux.Vars(r)
    mobilephone := vars["mobilephone"]
    output := vars["output"]
    willbesentdate := vars["willbesentdate"]
    sentdate := vars["sentdate"]
    status := vars["status"]

Gorilla 会期望这些都是请求路径中存在的值 ( /{mobilephone}/{output}/{willbesentdate}。我怀疑情况并非如此,因为您还将请求正文读入了结构。

删除该部分并且不要使用这些值,使用加载到结构中的值。


推荐阅读