Browse Source

Ch1 pp58-62 inserting users in MySQL. Use the db.sql file.

Frederic G. MARAND 8 years ago
parent
commit
2e1ad6ebf2
5 changed files with 61 additions and 2 deletions
  1. 2 2
      ch1/db.sql
  2. 0 0
      ch1/ex1/ex1_helloworld.go
  3. 0 0
      ch1/ex2/ex2_hellogorilla.go
  4. 0 0
      ch1/ex3/ex3_hellodrone.go
  5. 59 0
      ch1/ex4/ex4_user_create.go

+ 2 - 2
ch1/db.sql

@@ -26,8 +26,8 @@ SET time_zone = "+00:00";
 -- Structure de la table `user`
 --
 
-DROP TABLE IF EXISTS `user`;
-CREATE TABLE IF NOT EXISTS `user` (
+DROP TABLE IF EXISTS `users`;
+CREATE TABLE IF NOT EXISTS `users` (
   `user_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
   `user_nickname` varchar(32) NOT NULL,
   `user_first` varchar(32) NOT NULL,

+ 0 - 0
ch1/ex1_helloworld.go → ch1/ex1/ex1_helloworld.go


+ 0 - 0
ch1/ex2_hellogorilla.go → ch1/ex2/ex2_hellogorilla.go


+ 0 - 0
ch1/ex3_hellodrone.go → ch1/ex3/ex3_hellodrone.go


+ 59 - 0
ch1/ex4/ex4_user_create.go

@@ -0,0 +1,59 @@
+package main
+
+import (
+	"database/sql"
+	_ "github.com/go-sql-driver/mysql"
+	"encoding/json"
+	"fmt"
+	"github.com/gorilla/mux"
+	"net/http"
+)
+
+type API struct {
+	Message string "json:message"
+}
+
+type User struct {
+	ID int "json:id"
+	Name string "json:username"
+	Email string "json:email"
+	First string "json:first"
+	Last string "json:last"
+}
+
+var database *sql.DB
+func CreateUser(w http.ResponseWriter, r *http.Request) {
+	NewUser := User{}
+	NewUser.Name = r.FormValue("user")
+	NewUser.Email = r.FormValue("email")
+	NewUser.First = r.FormValue("first")
+	NewUser.Last = r.FormValue("last")
+	output, err := json.Marshal(NewUser)
+	if err != nil {
+		fmt.Println("Something went wrong with Marshal", err)
+	}
+	fmt.Println(string(output))
+
+	sql := "INSERT INTO users SET user_nickname='" + NewUser.Name + "'" + ", user_first = '" + NewUser.First + "'" + ", user_last = '" + NewUser.Last + "'" + ", user_email = '" + NewUser.Email + "';"
+	q, err := database.Exec(sql)
+	if err != nil {
+		fmt.Println("Something went wrong with INSERT", err)
+	}
+	last, err := q.LastInsertId()
+	affected, err := q.RowsAffected()
+	fmt.Printf("Last Id: %d, Affected rows: %d\n", last, affected)
+}
+
+func main() {
+	db, err := sql.Open("mysql", "goroot:gopass@/go_sn")
+	if err != nil {
+		fmt.Println("Something went wrong with sql.Open", err)
+		return
+	}
+	database = db
+
+	routes := mux.NewRouter()
+	routes.HandleFunc("/api/user/create", CreateUser).Methods("GET")
+	http.Handle("/", routes)
+	http.ListenAndServe(":8080", nil)
+}