commit 261fe15e7613d583d2089a58e60d9b5e671a4088 Author: diegomb Date: Thu May 30 16:19:38 2024 -0600 mi primer commit diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..b3f125c --- /dev/null +++ b/go.mod @@ -0,0 +1,5 @@ +module modulo1 + +go 1.18 + +require github.com/lib/pq v1.10.9 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..aeddeae --- /dev/null +++ b/go.sum @@ -0,0 +1,2 @@ +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= diff --git a/main.go b/main.go new file mode 100644 index 0000000..4c27eda --- /dev/null +++ b/main.go @@ -0,0 +1,85 @@ +package main + +import ( + "database/sql" + "fmt" + "log" + "net/http" + + _ "github.com/lib/pq" +) + +const ( + host = "45.79.210.141" + port = 5432 + user = "postgres" + password = "shae3Hai.dot" + dbname = "diegodb" +) + +type Jedi struct { + Name string `json:"name"` + Color string `json:"color"` + Era string `json:"era"` +} + +func main() { + http.HandleFunc("/create", createJedi) + http.HandleFunc("/retrieve", retrieveJedi) + http.HandleFunc("/delete", deleteJedi) + http.HandleFunc("/list", listJedi) // Nuevo endpoint para listar Jedi + + log.Fatal(http.ListenAndServe(":8080", nil)) +} + +func createJedi(w http.ResponseWriter, r *http.Request) { + // Implementación para crear un nuevo Jedi +} + +func retrieveJedi(w http.ResponseWriter, r *http.Request) { + // Implementación para recuperar un Jedi +} + +func deleteJedi(w http.ResponseWriter, r *http.Request) { + // Implementación para eliminar un Jedi +} + +func listJedi(w http.ResponseWriter, r *http.Request) { + // Retrieve all Jedi from database + db, err := sql.Open("postgres", fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer db.Close() + + rows, err := db.Query("SELECT jedi, color, era FROM sables_de_luz") + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + defer rows.Close() + + var jediList []Jedi + for rows.Next() { + var jedi Jedi + if err := rows.Scan(&jedi.Name, &jedi.Color, &jedi.Era); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + jediList = append(jediList, jedi) + } + if err := rows.Err(); err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // Construir una cadena con los nombres, colores y eras de los Jedi con saltos de línea + var response string + for _, jedi := range jediList { + response += fmt.Sprintf("%s, Color %s, Era %s\n", jedi.Name, jedi.Color, jedi.Era) + } + + // Escribir la respuesta en la respuesta HTTP + fmt.Fprintf(w, response) +}