Working broadcast and accurate response

This commit is contained in:
Sebastien Laithier 2023-05-10 15:25:03 +02:00
parent 6ee48dd629
commit fe42c2e3d4

27
main.go
View File

@ -15,6 +15,7 @@ const (
var (
varnishList = MakeVarnishList()
status = "200 Purged"
)
// MakeVarnishList reads the list of varnish servers from a file on disk.
@ -29,34 +30,36 @@ func MakeVarnishList() []string {
// PurgeHandler handles PURGE request to broadcast it to all varnish instances.
func PurgeHandler(w http.ResponseWriter, r *http.Request) {
var resp http.Response
url := r.URL.String()
SendToVarnish(url)
io.WriteString(w, resp.Status)
status := SendToVarnish(url)
if status != "200 Purged" {
w.WriteHeader(http.StatusMethodNotAllowed)
}
io.WriteString(w, status)
}
func SendToVarnish(url string) int {
var status int
var respListStatus []string
func SendToVarnish(url string) string {
status = "200 Purged"
// Take url to ban as argument.
// Loop over the list of Varnish servers and send PURGE request to each.
for i := 0; i < len(varnishList); i++ {
//status = "200 Purged"
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)
log.Fatal("NewRequest: %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.Printf("Resp: %v\n", resp)
if resp.StatusCode != 200 {
status = "405 Not Allowed"
}
fmt.Println("Purge URL" + " " + domain + url + " : " + status)
}
fmt.Println(respListStatus)
return status
}