Broadcast working

This commit is contained in:
Sebastien Laithier 2023-05-10 12:29:20 +02:00
parent 8ef58bc9e8
commit b9dd0db98b
2 changed files with 41 additions and 5 deletions

45
main.go
View File

@ -5,25 +5,60 @@ import (
"io" "io"
"log" "log"
"net/http" "net/http"
"os"
"strings"
) )
const ( const (
MethodPurge = "PURGE" MethodPurge = "PURGE"
) )
var (
varnishList = MakeVarnishList()
)
// MakeVarnishList reads the list of varnish servers from a file on disk.
func MakeVarnishList() []string {
Data, err := os.ReadFile("./varnish")
if err != nil {
log.Fatal(err)
}
sliceData := strings.Split(string(Data), ",")
return sliceData
}
// PurgeHandler handles PURGE request to broadcast it to all varnish instances. // PurgeHandler handles PURGE request to broadcast it to all varnish instances.
func PurgeHandler(w http.ResponseWriter, r *http.Request) { func PurgeHandler(w http.ResponseWriter, r *http.Request) {
client := &http.Client{} var resp http.Response
// Retrieve URL sent and send an HTTP PURGE request to all varnish servers. // Retrieve URL sent and send an HTTP PURGE request to all varnish servers.
url := r.URL.String() url := r.URL.String()
req, err := http.NewRequest(MethodPurge, "http://10.13.32.1:6081" + url, nil) SendToVarnish(url)
resp, err := client.Do(req)
fmt.Printf("Error: %v\n", err)
fmt.Printf("Resp: %v\n", resp)
io.WriteString(w, resp.Status) io.WriteString(w, resp.Status)
} }
func SendToVarnish(url string) int {
var status int
var respListStatus []string
for i := 0; i < len(varnishList); i++ {
client := &http.Client{}
domain := strings.Trim(varnishList[i], "\r\n")
req, err := http.NewRequest(MethodPurge, domain + url, nil)
//fmt.Printf("Request: %v",req)
if err != nil {
log.Fatal("NewRquest: %s", err)
}
resp, err := client.Do(req)
if err != nil {
log.Fatal("Client.do: %s", err)
}
fmt.Printf("Resp: %v\n", resp)
respListStatus = append(respListStatus, resp.Status)
}
fmt.Println(respListStatus)
return status
}
func main() { func main() {
http.HandleFunc("/", PurgeHandler) http.HandleFunc("/", PurgeHandler)
log.Fatal(http.ListenAndServe(":6081",nil)) log.Fatal(http.ListenAndServe(":6081",nil))

1
varnish Normal file
View File

@ -0,0 +1 @@
http://10.13.32.1:6081,http://10.13.32.2:6081