2023-06-02 15:47:33 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"html/template"
|
|
|
|
"net/http"
|
|
|
|
"os"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
func readWebsitesFromFile(filepath string) ([]WebsiteStatus, error) {
|
|
|
|
file, err := os.Open(filepath)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
|
|
|
var websites []WebsiteStatus
|
|
|
|
scanner := bufio.NewScanner(file)
|
|
|
|
for scanner.Scan() {
|
|
|
|
line := scanner.Text()
|
|
|
|
fields := strings.Split(line, ",")
|
|
|
|
if len(fields) != 4 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
|
|
|
|
hasIcon, _ := strconv.ParseBool(fields[2])
|
|
|
|
|
|
|
|
website := WebsiteStatus{
|
|
|
|
WebsiteURL: fields[0],
|
|
|
|
Description: fields[1],
|
|
|
|
HasIcon: hasIcon,
|
|
|
|
IconURL: fields[3],
|
|
|
|
}
|
|
|
|
|
|
|
|
websites = append(websites, website)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return websites, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func checkWebsite(website string) error {
|
|
|
|
client := &http.Client{
|
|
|
|
Timeout: 5 * time.Second, // Set a timeout for the request
|
|
|
|
}
|
|
|
|
|
|
|
|
response, err := client.Head(website)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer response.Body.Close()
|
|
|
|
|
|
|
|
if response.StatusCode != http.StatusOK {
|
|
|
|
return fmt.Errorf("status code: %d", response.StatusCode)
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func handleCheck(w http.ResponseWriter, r *http.Request) {
|
|
|
|
url := r.URL.Query().Get("url")
|
|
|
|
isUp := checkWebsite(url) == nil
|
|
|
|
response := struct {
|
|
|
|
IsUp bool `json:"isUp"`
|
|
|
|
}{
|
|
|
|
IsUp: isUp,
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
json.NewEncoder(w).Encode(response)
|
|
|
|
}
|
|
|
|
|
|
|
|
func renderTemplate(w http.ResponseWriter, statuses []WebsiteStatus) {
|
|
|
|
t, err := template.ParseFiles("template.html")
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
err = t.Execute(w, statuses)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
}
|
|
|
|
}
|
2023-06-02 17:06:48 +02:00
|
|
|
|
|
|
|
func maxLength(strings ...string) int {
|
|
|
|
maxLen := 0
|
|
|
|
for _, str := range strings {
|
|
|
|
if len(str) > maxLen {
|
|
|
|
maxLen = len(str)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return maxLen
|
|
|
|
}
|