virtigo/me.go

85 lines
1.8 KiB
Go
Raw Normal View History

2025-03-10 07:53:11 -05:00
package main
// RFC implementation
import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net"
"net/http"
"os/user"
"time"
)
// Function to create a persistent TCP connection
func createPersistentConnection(host string) (net.Conn, error) {
dialer := &net.Dialer{
Timeout: 10 * time.Second,
KeepAlive: 30 * time.Second,
}
conn, err := dialer.Dial("tcp", host)
if err != nil {
return nil, fmt.Errorf("failed to establish connection: %w", err)
}
return conn, nil
}
func mesocket() {
host := "example.com:80"
// Establish a persistent TCP connection
conn, err := createPersistentConnection(host)
if err != nil {
fmt.Println("Error creating connection:", err)
return
}
defer conn.Close()
// Custom transport that forces HTTP requests to use our existing connection
transport := &http.Transport{
DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
fmt.Println("Reusing existing TCP connection")
return conn, nil
},
DisableKeepAlives: false, // Ensure Keep-Alive is enabled
}
client := &http.Client{
Transport: transport,
Timeout: 10 * time.Second,
}
url := "http://example.com/endpoint"
data := []byte(`{"message": "Hello"}`)
// Create an HTTP request
req, err := http.NewRequest(http.MethodPost, url, bytes.NewBuffer(data))
if err != nil {
fmt.Println("Error creating request:", err)
return
}
usr, _ := user.Current()
req.Header.Set("author", usr.Username)
req.Header.Set("Connection", "keep-alive") // Keep connection alive
// Perform the HTTP request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error performing request:", err)
return
}
defer resp.Body.Close()
// Read and print the response
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response:", err)
return
}
fmt.Println("Response:", string(body))
}