Advertisement
Guest User

Untitled

a guest
Apr 1st, 2019
185
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.10 KB | None | 0 0
  1. type user struct {
  2. ID int `json:"id"`
  3. Username string `json:"username"`
  4. Password string `json:"password"`
  5. Email string `json:"email"`
  6. Phone int `json:"phone"`
  7. Country string `json:"country"`
  8. City string `json:"city"`
  9. PostCode int `json:"postcode"`
  10. Name string `json:"name"`
  11. Address string `json:"address"`
  12. }
  13.  
  14. //handler nya
  15. func Create(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
  16. user, err := createUser(r)
  17. if err != nil {
  18. http.Error(w, http.StatusText(500), http.StatusInternalServerError)
  19. log.Panic(err)
  20. return
  21. }
  22.  
  23. response, err := json.Marshal(user)
  24. if err != nil {
  25. http.Error(w, http.StatusText(406), http.StatusNotAcceptable)
  26. return
  27. }
  28.  
  29. w.Header().Set("Content-Type", "application/json")
  30. w.WriteHeader(http.StatusCreated)
  31. fmt.Fprintf(w, "%s", response)
  32. // w.Write(response)
  33. }
  34.  
  35. //function nya
  36. func createUser(r *http.Request) (user, error) {
  37. u := user{}
  38.  
  39. json.NewDecoder(r.Body).Decode(&u)
  40.  
  41. fmt.Println(u)
  42. if u.Username == "" || u.Email == "" || u.Name == "" || u.Password == "" || u.Address == "" || u.Phone == 0 || u.PostCode == 0 || u.City == "" || u.Country == "" {
  43. return u, errors.New("400. Bad request. All fields must be complete")
  44. }
  45.  
  46. hashPassword, err := generatePassword(u.Password)
  47. if err != nil {
  48. return u, err
  49. }
  50. u.Password = hashPassword
  51.  
  52. tx, err := config.DB.Begin()
  53. if err != nil {
  54. return u, err
  55. }
  56.  
  57. defer tx.Rollback()
  58.  
  59. stmt, err := tx.Prepare("INSERT INTO users(username, password, email, phone, country, city, postcode, name, address) VALUES(?,?,?,?,?,?,?,?,?) ")
  60. if err != nil {
  61. return u, err
  62. }
  63.  
  64. defer stmt.Close() // danger!
  65.  
  66. response, err := stmt.Exec(u.Username, u.Email, u.Password, u.Email, u.Phone, u.Country, u.City, u.PostCode, u.Name, u.Address)
  67. if err != nil {
  68. log.Fatal(err)
  69. return u, err
  70. }
  71.  
  72. err = tx.Commit()
  73. if err != nil {
  74. return u, err
  75. }
  76. lastID, err := response.LastInsertId()
  77. if err != nil {
  78. return u, err
  79. }
  80. u.ID = int(lastID)
  81. return u, nil
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement