89 lines
2 KiB
Go
89 lines
2 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
connCode = "secretcode123"
|
|
testMsg = "This is a test message"
|
|
)
|
|
|
|
var connCodeMutex sync.Mutex
|
|
var peers = []string{"localhost:50002", "localhost:5000"} // Example peer addresses
|
|
|
|
func handleNodeRequest(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
|
|
connCodeMutex.Lock()
|
|
defer connCodeMutex.Unlock()
|
|
|
|
body, err := ioutil.ReadAll(r.Body)
|
|
if err != nil {
|
|
http.Error(w, "Error reading request body", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
defer r.Body.Close()
|
|
|
|
receivedCode := strings.TrimSpace(string(body))
|
|
|
|
if receivedCode != connCode {
|
|
http.Error(w, "Authentication failed", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
fmt.Println("Authentication successful")
|
|
fmt.Fprintln(w, testMsg)
|
|
}
|
|
|
|
func startNodeClient(addresses []string) {
|
|
for _, address := range addresses {
|
|
go func(addr string) {
|
|
for {
|
|
url := fmt.Sprintf("http://%s/node", addr)
|
|
req, err := http.NewRequest(http.MethodPost, url, strings.NewReader(connCode))
|
|
if err != nil {
|
|
fmt.Println("Error creating request:", err)
|
|
time.Sleep(5 * time.Second)
|
|
continue
|
|
}
|
|
|
|
client := &http.Client{}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
fmt.Println("Error connecting to", addr, ":", err)
|
|
time.Sleep(5 * time.Second)
|
|
continue
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
fmt.Println("Authentication failed:", resp.Status)
|
|
resp.Body.Close()
|
|
time.Sleep(5 * time.Second)
|
|
continue
|
|
}
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
if err != nil {
|
|
fmt.Println("Error reading response:", err)
|
|
resp.Body.Close()
|
|
time.Sleep(5 * time.Second)
|
|
continue
|
|
}
|
|
resp.Body.Close()
|
|
|
|
testMsg := strings.TrimSpace(string(body))
|
|
fmt.Println("Received test message from", addr, ":", testMsg)
|
|
time.Sleep(10 * time.Second)
|
|
}
|
|
}(address)
|
|
}
|
|
}
|