1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- 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)
- }
|