Created
June 30, 2017 15:18
-
-
Save sylvie19791/88b873e16da3b4a3fb82c6bfdcd1837e to your computer and use it in GitHub Desktop.
Api Rest com Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "log" | |
| "net/http" | |
| "encoding/json" | |
| "io/ioutil" | |
| "github.com/gorilla/mux" | |
| ) | |
| func main() { | |
| rotas := mux.NewRouter().StrictSlash(true) | |
| rotas.HandleFunc("/membros", getMembros).Methods("GET") | |
| rotas.HandleFunc("/membros", postMembros).Methods("POST") | |
| log.Fatal(http.ListenAndServe(":3000", rotas)) | |
| } | |
| type Membro struct { | |
| ID uint `json:"id"` | |
| Nome string `json:"nome"` | |
| } | |
| var membros = []Membro{ | |
| Membro{ID: 1, Nome: "Marcus Mann"}, | |
| Membro{ID: 2, Nome: "Aline Marquez"}, | |
| } | |
| func getMembros(w http.ResponseWriter, r *http.Request) { | |
| w.Header().Set("Content-Type", "application/json") | |
| json.NewEncoder(w).Encode(membros) | |
| } | |
| func postMembros(w http.ResponseWriter, r *http.Request) { | |
| var t Membro | |
| body, _ := ioutil.ReadAll(r.Body) | |
| json.Unmarshal(body, &t) | |
| membros = append(membros, t) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment