package app import ( "encoding/json" "fmt" uuid "github.com/nu7hatch/gouuid" "net/http" "time" ) type User struct { UserID int Title string CreatedOn time.Time } type Users struct { users []User } func UserGetHandler(w http.ResponseWriter, req *http.Request) { if req.Method == "GET" { title, ok := req.URL.Query()["title"] if !ok || len(title[0]) < 1 { http.Error(w, "Url Param 'title' is missing", 400) return } // Query()["key"] will return an array of items, // we only want the single item. userTitle := title[0] users := Users{} err := queryRepos(&users, userTitle) if err != nil { http.Error(w, err.Error(), 500) return } if len(users.users) > 0 { out, err := json.Marshal(users.users) if err != nil { http.Error(w, err.Error(), 500) return } fmt.Fprintf(w, string(out)) } else { fmt.Fprintf(w, "User does not exist") } } else { fmt.Fprintf(w, "Sorry, only Get methods are supported for thus api.") } } func UserPostHandler(w http.ResponseWriter, req *http.Request) { if req.Method == "POST" { if err := req.ParseForm(); err != nil { fmt.Fprintf(w, "ParseForm() err: %v", err) return } uuid, err := uuid.NewV4() if err != nil { http.Error(w, err.Error(), 500) } title := req.FormValue("title") sqlInsert := ` INSERT INTO users (title, created_on,uuid) VALUES ($1, $2, $3) RETURNING user_id` if len(title) > 0 { user_id := 0 row := Db.QueryRow(sqlInsert, title, time.Now().Format(time.RFC3339), uuid.String()) err := row.Scan(&user_id) if err != nil { panic(err) } fmt.Fprintf(w, "user created.") } else { fmt.Fprintf(w, "Invalid data") } } else { fmt.Fprintf(w, "Sorry, only POST methods are supported for thus api.") } } func queryRepos(users *Users, userTitle string) error { query := ` SELECT user_id, title, created_on FROM users WHERE title='` + userTitle + `'; ` rows, err := Db.Query(query) if err != nil { return err } defer rows.Close() for rows.Next() { user := User{} err = rows.Scan( &user.UserID, &user.Title, &user.CreatedOn, ) if err != nil { return err } users.users = append(users.users, user) } err = rows.Err() if err != nil { return err } return nil }