I have problem with method post using gorilla/mux, and gorm, I want to request in body raw, but my code is error when I EXEC my procedure, why my code error? I'm still not understand to using request in body using gorilla/mux and gorm, how make post form using mux and gorm in golang?
My error is:
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()
}
There isn't a lot of data to go off of here, but it seems like you're accessing the wrong values and getting blank strings in return.
vars := mux.Vars(r)
mobilephone := vars["mobilephone"]
output := vars["output"]
willbesentdate := vars["willbesentdate"]
sentdate := vars["sentdate"]
status := vars["status"]
Gorilla would expect those all to be values present in the request path (/{mobilephone}/{output}/{willbesentdate}
. I suspect that isn't the case since you also read in the request body into the struct.
Remove that part and don't use those values, use the values that are loaded into your struct.