Mudanças entre as edições de "Go: RESTful - manipulando uma array"
De Aulas
(Criou página com 'Afluentes: Sistemas Distribuídos e Mobile <syntaxhighlight lang=go> package main import ( "encoding/json" "fmt" "net/http" "slices" "strconv" ) func main() { vet...') |
|||
Linha 18: | Linha 18: | ||
router.HandleFunc("GET /strings", func(w http.ResponseWriter, r *http.Request) { | router.HandleFunc("GET /strings", func(w http.ResponseWriter, r *http.Request) { | ||
− | + | json.NewEncoder(w).Encode(vet) | |
− | |||
− | |||
− | |||
− | |||
− | |||
}) | }) | ||
Edição das 10h32min de 27 de março de 2024
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())
}
}