-
Notifications
You must be signed in to change notification settings - Fork 0
/
SimpleRestApi.go
114 lines (107 loc) · 3.13 KB
/
SimpleRestApi.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
//https://www.youtube.com/watch?v=pQAV8A9KLwk Golang, REST API CRUD
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
)
type task struct {
ID int `json:ID`
Name string `json:name`
Content string `json:Content`
}
type alltasks []task
var tasks = alltasks{
{
ID: 1,
Name: "Task One",
Content: "Some Content",
},
{
ID: 2,
Name: "Task Two",
Content: "Some Content Two",
},
}
func createTask(w http.ResponseWriter, r *http.Request) {
var newTask task
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil{
fmt.Fprintf(w,"Insert a valid task")
}
json.Unmarshal(reqBody, &newTask)
newTask.ID = len(tasks)+1
tasks = append(tasks, newTask)
w.Header().Set("Content-Type", "application/json") //cabecera de un objeto json
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(newTask)
}
func updateTask(w http.ResponseWriter, r *http.Request){
vars := mux.Vars(r)
taskID, err := strconv.Atoi(vars["id"])
var updateTask task
if err != nil{
fmt.Fprintf(w,"Invalid ID")
}
reqBody, err := ioutil.ReadAll(r.Body)
if err != nil{
fmt.Fprintf(w, "Entre un dato válido")
}
json.Unmarshal(reqBody, &updateTask)
for i, t := range tasks{
if t.ID == taskID{
tasks = append(tasks[:i], tasks[i+1:]...)
updateTask.ID = taskID
tasks = append(tasks, updateTask)
fmt.Fprintf(w, "La tarea con ID %v ha sido actualizada satisfactoriamente ",taskID)
}
}
}
func deleteTask(w http.ResponseWriter, r *http.Request){
vars := mux.Vars(r)
taskID, err := strconv.Atoi(vars["id"])
if err != nil{
fmt.Fprintf(w, "Invalid ID")
return
}
for i, task := range tasks{
if task.ID == taskID{
tasks = append(tasks[:i], tasks[i + 1:]...) //esta línea conserva los elementos que están antes y después del elemento encontrado. Ejemplo [a,b,c], si el elemento a eliminar es b entonces quedaría [a,c]
fmt.Fprintf(w,"La tarea con el ID %v ha sido eliminada", taskID) //%v muestra la variable en cuestión
}
}
}
func getTask(w http.ResponseWriter, r *http.Request){
vars := mux.Vars(r)
taskID, err := strconv.Atoi(vars["id"]) //Atoi convierte un string en entero
if err != nil{
fmt.Fprintf(w, "Invalid ID")
return
}
for _, task := range tasks{ //Este ciclo significa que recorre elemento a elemento de la lista "tasks"
if task.ID == taskID {
w.Header().Set("Content-Type", "application/json") //cabecera de un objeto json
json.NewEncoder(w).Encode(task) //esta línea devuelve los datos en formato json
}
}
}
func getTasks(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(tasks)
}
func indexRoute(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to my API")
}
func main(){
router := mux.NewRouter().StrictSlash(true)
router.HandleFunc("/", indexRoute)
router.HandleFunc("/tasks", getTasks).Methods("GET")
router.HandleFunc("/tasks", createTask).Methods("POST")
router.HandleFunc("/tasks/{id}", getTask).Methods("GET")
router.HandleFunc("/tasks/{id}", deleteTask).Methods("DELETE")
router.HandleFunc("/tasks/{id}", updateTask).Methods("PUT")
log.Fatal(http.ListenAndServe(":3000", router))
}