Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- type user struct {
- ID int `json:"id"`
- Username string `json:"username"`
- Password string `json:"password"`
- Email string `json:"email"`
- Phone int `json:"phone"`
- Country string `json:"country"`
- City string `json:"city"`
- PostCode int `json:"postcode"`
- Name string `json:"name"`
- Address string `json:"address"`
- }
- //handler nya
- func Create(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
- user, err := createUser(r)
- if err != nil {
- http.Error(w, http.StatusText(500), http.StatusInternalServerError)
- log.Panic(err)
- return
- }
- response, err := json.Marshal(user)
- if err != nil {
- http.Error(w, http.StatusText(406), http.StatusNotAcceptable)
- return
- }
- w.Header().Set("Content-Type", "application/json")
- w.WriteHeader(http.StatusCreated)
- fmt.Fprintf(w, "%s", response)
- // w.Write(response)
- }
- //function nya
- func createUser(r *http.Request) (user, error) {
- u := user{}
- json.NewDecoder(r.Body).Decode(&u)
- fmt.Println(u)
- if u.Username == "" || u.Email == "" || u.Name == "" || u.Password == "" || u.Address == "" || u.Phone == 0 || u.PostCode == 0 || u.City == "" || u.Country == "" {
- return u, errors.New("400. Bad request. All fields must be complete")
- }
- hashPassword, err := generatePassword(u.Password)
- if err != nil {
- return u, err
- }
- u.Password = hashPassword
- tx, err := config.DB.Begin()
- if err != nil {
- return u, err
- }
- defer tx.Rollback()
- stmt, err := tx.Prepare("INSERT INTO users(username, password, email, phone, country, city, postcode, name, address) VALUES(?,?,?,?,?,?,?,?,?) ")
- if err != nil {
- return u, err
- }
- defer stmt.Close() // danger!
- response, err := stmt.Exec(u.Username, u.Email, u.Password, u.Email, u.Phone, u.Country, u.City, u.PostCode, u.Name, u.Address)
- if err != nil {
- log.Fatal(err)
- return u, err
- }
- err = tx.Commit()
- if err != nil {
- return u, err
- }
- lastID, err := response.LastInsertId()
- if err != nil {
- return u, err
- }
- u.ID = int(lastID)
- return u, nil
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement