Hi,
Am trying to write a simple api using gorm and Sqlite3 database. Am using
stuct and functions below.
However, after "PUT" of JSON format payload using Postman, the instances
get created but when try
to "GET" all the instances, the array content shows "plmnList : null"
without the array key and values
even though i have provided values in the JSON PUT body.
Help needed, maybe am doing some wrong.
Thanks in advance.
example of PUT json payload using Postman
{
"nfInstanceId": "3fa85f64-5717-4562-b3fc-2c96322333",
"plmnList":[{
"mcc": "446",
"mnc": "336"
}],
"validityPeriod":44
}
// Struct
type NfInstanceStore struct {
NfInstanceID string `json:"nfInstanceId" gorm:"primary_key"`
PlmnList [ ]PlmnList `json:"plmnList"`
ValidityPeriod int `json:" validityPeriod"`
}
type PlmnList struct {
gorm.Model
Mcc string `json:"mcc"`
Mnc string `json:"mnc"`
}
// Database migration
var db *gorm.DB
var e error
func initialMigration() {
db, e := gorm.Open("sqlite3", "gorm.db")
if e != nil {
fmt.Println(e.Error())
panic("failed to connect database")
}
defer db.Close()
// Migrate the schema
db.AutoMigrate(&model.NfInstanceStore{}, &model.PlmnList{})
}
// Main function is as follow
func main() {
initialMigration()
router := mux.NewRouter()
router.HandleFunc("/nnrf-nmf/v1/nf-instances",
getAllNFInstances).Methods("GET")
router.HandleFunc("/nnrf-nmf/v1/nf-instances/{nfinstanceID}",
registerNewNFInstance).Methods("PUT")
}
// PUT - registerNewNFInstance
func registerNewNFInstance(w http.ResponseWriter, r *http.Request) {
db, err := gorm.Open("sqlite3", "gorm.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
nfinstance := model.NfInstanceStore{}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&nfinstance); err != nil {
respondError(w, http.StatusBadRequest, err.Error())
return
}
defer r.Body.Close()
if err := db.Save(&nfinstance).Error; err != nil {
respondError(w, http.StatusInternalServerError, err.Error())
return
}
respondJSON(w, http.StatusCreated, nfinstance)
}
// GETAll
func getAllNFInstances(w http.ResponseWriter, r *http.Request) {
db, err := gorm.Open("sqlite3", "gorm.db")
if err != nil {
panic("failed to connect database")
}
defer db.Close()
nfinstances := []model.NfInstanceStore{}
db.Find(&nfinstances)
respondJSON(w, http.StatusOK, nfinstances)
}
//
func respondJSON(w http.ResponseWriter, status int, payload interface{}) {
response, err := json.Marshal(payload)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
w.Write([]byte(response))
}
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.