Bläddra i källkod

commit inicial

Rodrigo.Rodrigo 1 år sedan
incheckning
f8588a1d14
5 ändrade filer med 95 tillägg och 0 borttagningar
  1. 3 0
      go.mod
  2. 15 0
      main.go
  3. 35 0
      server/handlers.go
  4. 25 0
      server/routes.go
  5. 17 0
      server/server.go

+ 3 - 0
go.mod

@@ -0,0 +1,3 @@
+module Go
+
+go 1.23.1

+ 15 - 0
main.go

@@ -0,0 +1,15 @@
+package main
+
+import (
+	"Go/server"
+)
+
+func main() {
+
+	srv := server.New(":8080")
+	err := srv.ListenAndServe()
+
+	if err != nil {
+		panic(err)
+	}
+}

+ 35 - 0
server/handlers.go

@@ -0,0 +1,35 @@
+package server
+
+import (
+	"encoding/json"
+	"fmt"
+	"net/http"
+)
+
+func index(w http.ResponseWriter, r *http.Request) {
+	if r.Method != http.MethodGet {
+		w.WriteHeader(http.StatusMethodNotAllowed)
+		fmt.Fprintf(w, "method not allowed")
+		return
+	}
+	fmt.Fprintf(w, "Hellow there %s", "visitor")
+}
+
+func getCountries(w http.ResponseWriter, _ *http.Request) {
+	w.Header().Set("Content-Type", "application/json")
+	json.NewEncoder(w).Encode(countries)
+}
+func addCountry(w http.ResponseWriter, r *http.Request) {
+
+	country := &Country{}
+
+	err := json.NewDecoder(r.Body).Decode(country)
+	if err != nil {
+		w.WriteHeader(http.StatusBadRequest)
+		fmt.Fprintf(w, "%v", err)
+		return
+	}
+
+	countries = append(countries, country)
+	fmt.Fprintf(w, "country was added")
+}

+ 25 - 0
server/routes.go

@@ -0,0 +1,25 @@
+package server
+
+import (
+	"fmt"
+	"net/http"
+)
+
+func initRoutes() {
+	http.HandleFunc("/", index)
+
+	http.HandleFunc("/countries", func(w http.ResponseWriter, r *http.Request) {
+		switch r.Method {
+		case http.MethodGet:
+			getCountries(w, r)
+
+		case http.MethodPost:
+			addCountry(w, r)
+
+		default:
+			w.WriteHeader(http.StatusMethodNotAllowed)
+			fmt.Fprintf(w, "Method not allowed")
+			return
+		}
+	})
+}

+ 17 - 0
server/server.go

@@ -0,0 +1,17 @@
+package server
+
+import "net/http"
+
+type Country struct {
+	Name     string
+	Language string
+}
+
+var countries []*Country = []*Country{}
+
+func New(addr string) *http.Server {
+	initRoutes()
+	return &http.Server{
+		Addr: addr,
+	}
+}