Add HTTPProber widget and API to display website statuses
This commit is contained in:
86
apis/httpprober/main.go
Normal file
86
apis/httpprober/main.go
Normal file
@@ -0,0 +1,86 @@
|
||||
package httpprober
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const websitesFile = "websites.json"
|
||||
|
||||
type Website struct {
|
||||
URL string `json:"url"`
|
||||
Icon string `json:"icon"`
|
||||
Status int `json:"status"`
|
||||
}
|
||||
|
||||
func RunProbe() []Website {
|
||||
results := make([]Website, 0)
|
||||
websites := websites()
|
||||
|
||||
client, err := buildHTTPClient()
|
||||
if err != nil {
|
||||
return websites
|
||||
}
|
||||
|
||||
for _, website := range websites {
|
||||
if website.URL != "" && !strings.Contains(website.URL, "://") {
|
||||
website.URL = "https://" + website.URL
|
||||
}
|
||||
website.Status = testMethod(client, website)
|
||||
results = append(results, website)
|
||||
}
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
func websites() []Website {
|
||||
websites := make([]Website, 0)
|
||||
file, err := os.ReadFile(websitesFile)
|
||||
if err == nil {
|
||||
if err := json.Unmarshal(file, &websites); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
return websites
|
||||
}
|
||||
|
||||
func buildHTTPClient() (*http.Client, error) {
|
||||
timeout := 10
|
||||
|
||||
client := &http.Client{
|
||||
Timeout: time.Duration(timeout) * time.Second,
|
||||
}
|
||||
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: &tls.Config{},
|
||||
}
|
||||
|
||||
client.Transport = transport
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func testMethod(client *http.Client, target Website) int {
|
||||
req, err := http.NewRequest("GET", target.URL, nil)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return -2
|
||||
}
|
||||
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
return -1
|
||||
}
|
||||
defer func(body io.ReadCloser) {
|
||||
_ = body.Close()
|
||||
}(resp.Body)
|
||||
|
||||
return resp.StatusCode
|
||||
}
|
||||
Reference in New Issue
Block a user