ex6_headers.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package main
  2. import (
  3. "database/sql"
  4. "encoding/json"
  5. "fmt"
  6. _ "github.com/go-sql-driver/mysql"
  7. "github.com/gorilla/mux"
  8. "log"
  9. "net/http"
  10. )
  11. type API struct {
  12. Message string "json:message"
  13. }
  14. type User struct {
  15. ID int "json:id"
  16. Name string "json:username"
  17. Email string "json:email"
  18. First string "json:first"
  19. Last string "json:last"
  20. }
  21. var database *sql.DB
  22. func CreateUser(w http.ResponseWriter, r *http.Request) {
  23. NewUser := User{}
  24. NewUser.Name = r.FormValue("user")
  25. NewUser.Email = r.FormValue("email")
  26. NewUser.First = r.FormValue("first")
  27. NewUser.Last = r.FormValue("last")
  28. output, err := json.Marshal(NewUser)
  29. if err != nil {
  30. fmt.Println("Something went wrong with Marshal", err)
  31. }
  32. fmt.Println(string(output))
  33. sql := "INSERT INTO users SET user_nickname='" + NewUser.Name + "'" +
  34. ", user_first = '" + NewUser.First + "'" +
  35. ", user_last = '" + NewUser.Last + "'" +
  36. ", user_email = '" + NewUser.Email + "';"
  37. q, err := database.Exec(sql)
  38. if err != nil {
  39. fmt.Println("Something went wrong with INSERT", err)
  40. }
  41. last, err := q.LastInsertId()
  42. affected, err := q.RowsAffected()
  43. fmt.Printf("Last Id: %d, Affected rows: %d\n", last, affected)
  44. }
  45. func GetUser(w http.ResponseWriter, r *http.Request) {
  46. header := w.Header()
  47. header.Set("Pragma", "no-cache")
  48. urlParams := mux.Vars(r)
  49. id := urlParams["id"]
  50. ReadUser := User{}
  51. err := database.QueryRow("SELECT * FROM users WHERE user_id=?", id).Scan(
  52. &ReadUser.ID,
  53. &ReadUser.Name,
  54. &ReadUser.First,
  55. &ReadUser.Last,
  56. &ReadUser.Email,
  57. )
  58. if err != nil {
  59. fmt.Println("Something went wrong with QueryRow", err)
  60. }
  61. switch {
  62. case err == sql.ErrNoRows:
  63. fmt.Fprintf(w, "No such user")
  64. case err != nil:
  65. log.Fatal(err)
  66. fmt.Fprint(w, "Error")
  67. default:
  68. output, _ := json.Marshal(ReadUser)
  69. header.Set("Content-type", "application/json")
  70. fmt.Fprint(w, string(output))
  71. }
  72. }
  73. func main() {
  74. db, err := sql.Open("mysql", "goroot:gopass@/go_sn")
  75. if err != nil {
  76. fmt.Println("Something went wrong with sql.Open", err)
  77. return
  78. }
  79. database = db
  80. routes := mux.NewRouter()
  81. routes.HandleFunc("/api/{id:[\\d]+}", GetUser).Methods("GET")
  82. routes.HandleFunc("/api/user/create", CreateUser).Methods("GET")
  83. http.Handle("/", routes)
  84. http.ListenAndServe(":8080", nil)
  85. }