Go: RESTful - manipulando uma array
De Aulas
Revisão de 12h38min de 1 de março de 2024 por Admin (discussão | contribs) (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...')
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) {
j, err := json.Marshal(vet)
if err != nil {
fmt.Printf("Error: %s", err.Error())
} else {
fmt.Fprintf(w, "%s", string(j))
}
})
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())
}
}