-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
74 lines (59 loc) · 1.55 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
func handleHomeRoute(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Welcome to the Home Route")
}
type Response struct {
Message string
Items []int
}
type RequestData struct {
Name string
LastName string
}
func sendData(w http.ResponseWriter, r *http.Request) {
// Create a response object
response := Response{
Message: "HELLO FROM BACKEND",
Items: []int{1, 2, 3},
}
// Encode the response struct to JSON and write it to the response writer
err := json.NewEncoder(w).Encode(response)
if err != nil {
http.Error(w, fmt.Sprintf("Error encoding JSON: %v", err), http.StatusInternalServerError)
return
}
}
func submitData(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
var data RequestData
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&data)
if err != nil {
http.Error(w, "Error decoding JSON", http.StatusBadRequest)
return
}
if data.Name == "" || data.LastName == "" {
log.Println("Name or LastName is missing")
http.Error(w, "Name or LastName is misisng", http.StatusBadRequest)
return
}
fmt.Println("Data Received:", data)
fmt.Println("Name", data.Name)
fmt.Println("LastName", data.LastName)
w.WriteHeader(http.StatusOK)
w.Write([]byte("Data successfully received"))
}
}
func main() {
http.HandleFunc("/", handleHomeRoute)
http.HandleFunc("/data", sendData)
http.HandleFunc("/submit-data", submitData)
fmt.Println("Starting Go server on :8080...")
http.ListenAndServe(":8080", nil)
}