Advertisement
Gabsness

Untitled

Mar 24th, 2019
547
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.52 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.     /*var users models.User*/
  7.  
  8.     user, _ = r.Context().Value("user").(models.User)
  9.  
  10.     /*err := json.NewDecoder(r.Body).Decode(&comment)*/
  11.     err := json.NewDecoder(r.Body).Decode(&comment)
  12.  
  13.     if err != nil {
  14.         m.Code = http.StatusBadRequest
  15.         m.Message = fmt.Sprintf("Error al leer el comentario: %s", err)
  16.         commons.DisplayMessage(w, m)
  17.         return
  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).Related(&comment.User)*/
  33.     db.Model(&comment).Related(&comment.User)
  34.     comment.User[0].Password = ""
  35.     db.LogMode(true)
  36.     /*fmt.Printf("%v+",comment)*/
  37.  
  38.  
  39.     j, err := json.Marshal(&comment)
  40.     if err != nil {
  41.         m.Code = http.StatusInternalServerError
  42.         m.Message = fmt.Sprintf("no se pudo convertir a json: %s", err)
  43.         commons.DisplayMessage(w, m)
  44.         return
  45.     }
  46.  
  47.     origin := fmt.Sprintf("localhost:%d/", commons.Port)
  48.     url := fmt.Sprintf("ws://localhost:%d/ws", commons.Port)
  49.     ws , err := websocket.Dial(url, "", origin)
  50.     if err != nil {
  51.         log.Fatal(err)
  52.     }
  53.     if _, err := ws.Write(j); err != nil {
  54.         log.Fatal(err)
  55.     }
  56.     m.Code = http.StatusCreated
  57.     m.Message = "Comentario creado con éxito"
  58.     commons.DisplayMessage(w, m)
  59.     return
  60.  
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement