Omitempty в структуре не опуская - PullRequest
0 голосов
/ 15 декабря 2018

Я пытаюсь сохранить данные в MongoDB без отправки нулевых данных.Рассматриваемая структура - это опрос и вопрос.Входящие данные могут варьироваться от 2 вопросов до 5. Поэтому, если пользователь вводит только 2 вопроса, у меня не будет необходимости использовать 3 других поля в структуре Poll.Я бы лучше не отображал поля, чем отправлял нулевые данные на сервер.

package main

// Omit Empty not working
type Poll struct {
Id     bson.ObjectId `bson:"_id"`
  Quest0 *Question     `json:"quest0,omitempty"`
  Quest1 *Question     `json:"quest1,omitempty"`
  Quest2 *Question     `json:"quest2,omitempty"`
  Quest3 *Question     `json:"quest3,omitempty"`
  Quest4 *Question     `json:"quest4,omitempty"`
  Quest5 *Question     `json:"quest5,omitempty"`
}

type Question struct {
  Count    *int    `json:"count,omitempty"`
  Question *string `json:"question,omitempty"`
}

type ReceivedPoll struct {
  Quest0 string `db:"quest0"`
  Quest1 string `db:"quest1"`
  Quest2 string `db:"quest2"`
  Quest3 string `db:"quest3"`
  Quest4 string `db:"quest4"`
  Quest5 string `db:"quest5"`
}

func main() {
  fmt.Println("server running...")

  router := httprouter.New()

  router.POST("/api/create", api)
  router.NotFound = http.FileServer(http.Dir("./public"))
  log.Fatal(http.ListenAndServe(":5000", router))
}

func api(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {

  w.Header().Set("Content-type", "application/json")

  session, err := mgo.Dial(mkey)

  if err != nil {
    panic(err)
  }

  defer session.Close()
  fmt.Println("is this running?")

  switch r.URL.String() {
    case "/api/create":
      // LOOK HERE
      poll := &Poll{}

      json.NewDecoder(r.Body).Decode(&poll)

      poll.Id = bson.NewObjectId()
      fmt.Println(*poll)

      c := session.DB("abase").C("polls")
      err = c.Insert(*poll)
      if err != nil {
        fmt.Println(err)
      }

      rz, _ := json.Marshal(poll.Id)
      w.Write(rz)
  }
}

1 Ответ

0 голосов
/ 15 декабря 2018

Добавьте ключ bson, используемый датчиком mgo BSON.Кодер игнорирует клавишу json.Подробности см. В документации bson.Marshal .

type Poll struct {
    Id     bson.ObjectId `bson:"_id"`
    Quest0 *Question     `json:"quest0,omitempty" bson:"ques0:omitempty"`
    ...
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...