ex4_user_create.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package main
  2. import (
  3. "database/sql"
  4. _ "github.com/go-sql-driver/mysql"
  5. "encoding/json"
  6. "fmt"
  7. "github.com/gorilla/mux"
  8. "net/http"
  9. )
  10. type API struct {
  11. Message string "json:message"
  12. }
  13. type User struct {
  14. ID int "json:id"
  15. Name string "json:username"
  16. Email string "json:email"
  17. First string "json:first"
  18. Last string "json:last"
  19. }
  20. var database *sql.DB
  21. func CreateUser(w http.ResponseWriter, r *http.Request) {
  22. NewUser := User{}
  23. NewUser.Name = r.FormValue("user")
  24. NewUser.Email = r.FormValue("email")
  25. NewUser.First = r.FormValue("first")
  26. NewUser.Last = r.FormValue("last")
  27. output, err := json.Marshal(NewUser)
  28. if err != nil {
  29. fmt.Println("Something went wrong with Marshal", err)
  30. }
  31. fmt.Println(string(output))
  32. sql := "INSERT INTO users SET user_nickname='" + NewUser.Name + "'" + ", user_first = '" + NewUser.First + "'" + ", user_last = '" + NewUser.Last + "'" + ", user_email = '" + NewUser.Email + "';"
  33. q, err := database.Exec(sql)
  34. if err != nil {
  35. fmt.Println("Something went wrong with INSERT", err)
  36. }
  37. last, err := q.LastInsertId()
  38. affected, err := q.RowsAffected()
  39. fmt.Printf("Last Id: %d, Affected rows: %d\n", last, affected)
  40. }
  41. func main() {
  42. db, err := sql.Open("mysql", "goroot:gopass@/go_sn")
  43. if err != nil {
  44. fmt.Println("Something went wrong with sql.Open", err)
  45. return
  46. }
  47. database = db
  48. routes := mux.NewRouter()
  49. routes.HandleFunc("/api/user/create", CreateUser).Methods("GET")
  50. http.Handle("/", routes)
  51. http.ListenAndServe(":8080", nil)
  52. }