Advertisement
Gabsness

Untitled

Mar 23rd, 2019
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.39 KB | None | 0 0
  1. func CreateComment(w http.ResponseWriter, r *http.Request) {
  2.     comment := models.Comment{}
  3.     user := models.User{}
  4.     m := models.Message{}
  5.  
  6.     user, _ = r.Context().Value("user").(models.User)
  7.  
  8.     err := json.NewDecoder(r.Body).Decode(&comment)
  9.     if err != nil {
  10.         m.Code = http.StatusBadRequest
  11.         m.Message = fmt.Sprintf("Error al leer el comentario: %s", err)
  12.         commons.DisplayMessage(w, m)
  13.         return
  14.     }
  15.  
  16.     comment.UserID = user.ID
  17.  
  18.     db := configuration.GetConnection()
  19.     defer db.Close()
  20.  
  21.     err = db.Create(&comment).Error
  22.     if err != nil {
  23.         m.Code = http.StatusBadRequest
  24.         m.Message = fmt.Sprintf("Error al crear el comentario: %s", err)
  25.         commons.DisplayMessage(w, m)
  26.         return
  27.     }
  28.  
  29.     db.Model(&comment).Related(&comment.User)
  30.     /* comment.User[0].Password = ""  */ /* El error está aquí */
  31.  
  32.     j, err := json.Marshal(&comment)
  33.     if err != nil {
  34.         m.Message = fmt.Sprintf("No se pudo convertir el comentario a json: %s", err)
  35.         m.Code = http.StatusInternalServerError
  36.         commons.DisplayMessage(w, m)
  37.         return
  38.     }
  39.  
  40.     origin := fmt.Sprintf("http://localhost:%d/", commons.Port)
  41.     url := fmt.Sprintf("ws://localhost:%d/ws", commons.Port)
  42.     ws, err := websocket.Dial(url, "", origin)
  43.     if err != nil {
  44.         log.Fatal(err)
  45.     }
  46.  
  47.     if _, err := ws.Write(j); err != nil {
  48.         log.Fatal(err)
  49.     }
  50.  
  51.     m.Code = http.StatusCreated
  52.     m.Message = "Comentario creado con éxito."
  53.     commons.DisplayMessage(w, m)
  54.  
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement