Go: RESTful - manipulando uma array
De Aulas
Afluentes: Sistemas Distribuídos e Mobile
package main
import (
"encoding/json"
"fmt"
"net/http"
"slices"
"strconv"
)
func main() {
vet := make([]string, 0)
router := http.NewServeMux()
router.HandleFunc("GET /strings", func(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(vet)
})
router.HandleFunc("GET /strings/{index}", func(w http.ResponseWriter, r *http.Request) {
index, err := strconv.Atoi(r.PathValue("index"))
if err != nil || index >= len(vet) {
fmt.Fprintf(w, "max position is %d", len(vet)-1)
return
}
out := vet[index]
fmt.Fprintf(w, "%s", out)
})
router.HandleFunc("POST /strings", func(w http.ResponseWriter, r *http.Request) {
strvet := make([]string, 0)
err := json.NewDecoder(r.Body).Decode(&strvet)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
vet = slices.Concat(vet, strvet)
})
router.HandleFunc("DELETE /strings/{index}", func(w http.ResponseWriter, r *http.Request) {
index, err := strconv.Atoi(r.PathValue("index"))
if err != nil || index >= len(vet) {
fmt.Fprintf(w, "wrong position %d", len(vet)-1)
return
}
vet = append(vet[:index], vet[index+1:]...)
})
if err := http.ListenAndServe("localhost:8080", router); err != nil {
fmt.Println(err.Error())
}
}