Advertisement
Gabsness

Codigo GO ( controller comment.go, method CreateComment)

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