Files
WB-status-api-server/app.go

101 lines
1.9 KiB
Go

package main
import (
"database/sql"
"net/http"
"os"
"time"
"github.com/gin-gonic/gin"
"github.com/go-yaml/yaml"
_ "github.com/mattn/go-sqlite3"
)
type Config struct {
General GeneralConfig `yaml:"general"`
Sites []SiteConfig `yaml:"sites"`
}
type GeneralConfig struct {
CacheTime int `yaml:"cachetime"`
DBType string `yaml:"dbtype"`
SQLAddr string `yaml:"sqladdr"`
}
type SiteConfig struct {
Name string `yaml:"name"`
URL string `yaml:"url"`
Type string `yaml:"type"`
}
var config Config
func main() {
// YAMLファイルを読み込む
data, err := os.Open("config.yaml")
if err != nil {
panic(err)
}
defer data.Close()
err = yaml.Unmarshal(data, &config)
if err != nil {
panic(err)
}
initdb()
r := gin.Default()
r.GET("/api/getStatus", func(c *gin.Context) {
// 全てのサイトのステータス情報をJSON形式で返す
})
r.GET("/api/getStatus/:URL", func(c *gin.Context) {
// 指定したサイトのステータス情報をJSON形式で返す
url := c.Param("URL", 0)
status := getstatus(url)
c.JSON(http.StatusOK, gin.H{
"url": url,
"status": status,
"checked_at": time.Now().Format("2006-01-02 15:04:05"),
})
})
r.Run(":8080")
}
func initdb(){
if config.General.DBType == "sqlite"{
db, err := sql.Open("sqlite3", config.General.SQLAddr)
if err != nil {
panic(err)
}
defer db.Close()
// テーブルの作成
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS sites (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
url TEXT NOT NULL,
type TEXT NOT NULL,
lastChecked DATETIME NOT NULL,
lastDowned DATETIME NOT NULL,
status TEXT NOT NULL
)`)
if err != nil {
panic(err)
}
}
}
func getstatus(url string) (int) {
//TODO: 鯖落ち検知時の返り値
r ,err := http.Head(url)
if err != nil {
return -1
}
defer r.Body.Close()
return r.StatusCode
}
func getstatusAll(url string) (string, string){
}