Skip to content

Instantly share code, notes, and snippets.

@zaz600
Last active January 31, 2016 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zaz600/16193edbf956d85a2a75 to your computer and use it in GitHub Desktop.
Save zaz600/16193edbf956d85a2a75 to your computer and use it in GitHub Desktop.
// web_check.go
package main
import (
"fmt"
"net/http"
"os"
"time"
)
const (
url = "https://golang.org/"
hist_length = 10 // сколько хранить записей в массиве с историей проверок
)
var check_history []string
func main() {
go check_loop()
http.HandleFunc("/", indexHandler)
http.ListenAndServe(":8088", nil)
}
func check_loop() {
for {
tm := time.Now().Format("2006-01-02 15:04:05")
// статус, который возвращает check, пока не используем, поэтому ставим _
_, msg := check(url)
log_to_file(tm, msg)
save_history(tm, msg)
fmt.Println(tm, msg)
time.Sleep(1 * time.Minute)
}
}
func check(url string) (bool, string) {
// возвращает true - если сервис доступен, false, если нет и текст сообщения
fmt.Println("Проверяем адрес ", url)
resp, err := http.Get(url)
if err != nil {
return false, fmt.Sprintf("Ошибка соединения. %s", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return false, fmt.Sprintf("Ошибка. http-статус: %s", resp.StatusCode)
}
return true, fmt.Sprintf("Онлайн. http-статус: %d", resp.StatusCode)
}
func log_to_file(tm, s string) {
// Сохраняет сообщения в файл
f, err := os.OpenFile("web_check.log", os.O_RDWR|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
fmt.Println(tm, err)
return
}
defer f.Close()
if _, err = f.WriteString(fmt.Sprintln(tm, s)); err != nil {
fmt.Println(tm, err)
}
}
func save_history(tm, s string) {
// добавляет запись в массив с историей проверок
check_history = append(check_history, fmt.Sprintf("%s %s", tm, s))
if len(check_history) > hist_length {
check_history = check_history[1:]
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
// Выдает историю проверок в браузер
var html = `<html><head><title>Проверка веб-службы</title></head><body><h1>История проверки</h1><div>%s</div></body></html>`
s := ""
for _, h := range check_history {
s += fmt.Sprintf("%s<br/>\n", h)
}
fmt.Fprintf(w, fmt.Sprintf(html, s))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment