handlers.go 754 B

1234567891011121314151617181920212223242526272829303132333435
  1. package server
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/http"
  6. )
  7. func index(w http.ResponseWriter, r *http.Request) {
  8. if r.Method != http.MethodGet {
  9. w.WriteHeader(http.StatusMethodNotAllowed)
  10. fmt.Fprintf(w, "method not allowed")
  11. return
  12. }
  13. fmt.Fprintf(w, "Hellow there %s", "visitor")
  14. }
  15. func getCountries(w http.ResponseWriter, _ *http.Request) {
  16. w.Header().Set("Content-Type", "application/json")
  17. json.NewEncoder(w).Encode(countries)
  18. }
  19. func addCountry(w http.ResponseWriter, r *http.Request) {
  20. country := &Country{}
  21. err := json.NewDecoder(r.Body).Decode(country)
  22. if err != nil {
  23. w.WriteHeader(http.StatusBadRequest)
  24. fmt.Fprintf(w, "%v", err)
  25. return
  26. }
  27. countries = append(countries, country)
  28. fmt.Fprintf(w, "country was added")
  29. }