package main import ( "database/sql" "encoding/json" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/gorilla/mux" "log" "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 GetUser(w http.ResponseWriter, r *http.Request) { header := w.Header() header.Set("Pragma", "no-cache") urlParams := mux.Vars(r) id := urlParams["id"] ReadUser := User{} err := database.QueryRow("SELECT * FROM users WHERE user_id=?", id).Scan( &ReadUser.ID, &ReadUser.Name, &ReadUser.First, &ReadUser.Last, &ReadUser.Email, ) if err != nil { fmt.Println("Something went wrong with QueryRow", err) } switch { case err == sql.ErrNoRows: fmt.Fprintf(w, "No such user") case err != nil: log.Fatal(err) fmt.Fprint(w, "Error") default: output, _ := json.Marshal(ReadUser) header.Set("Content-type", "application/json") fmt.Fprint(w, string(output)) } } 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/{id:[\\d]+}", GetUser).Methods("GET") routes.HandleFunc("/api/user/create", CreateUser).Methods("GET") http.Handle("/", routes) http.ListenAndServe(":8080", nil) }