test node messages
This commit is contained in:
parent
78c8fdbb4a
commit
30aa3d0238
7 changed files with 195 additions and 8 deletions
89
node.go
Normal file
89
node.go
Normal file
|
@ -0,0 +1,89 @@
|
|||
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)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue