You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
api/main.go

160 lines
4.4 KiB
Go

package main
import (
"errors"
"fmt"
"log"
docs "lsm-api/docs"
"net/http"
"strings"
"github.com/gin-gonic/gin"
swaggerfiles "github.com/swaggo/files"
ginSwagger "github.com/swaggo/gin-swagger"
"gopkg.in/ini.v1"
"lsm-api/models"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
var DB *gorm.DB
// @BasePath /api/v1
// @Summary Get all hosts in LSM
// @Description Lists all the hosts in LSM
// @Tags Hosts
// @Accept json
// @Produce json
// @Success 200 {object} []models.Host
// @Router /hosts/hosts [get]
func GetHosts(c *gin.Context) {
var hosts []models.Host
DB.Find(&hosts)
c.JSON(http.StatusOK, hosts)
}
// @Summary Get a host by hostname
// @Description Get a host by hostname
// @Tags Hosts
// @Accept json
// @Produce json
// @Param hostname path string true "The hostname to get the host by"
// @Success 200 {object} models.Host
// @Router /hosts/get_host_by_hostname/{hostname} [get]
func GetHostByHostname(c *gin.Context) {
var host models.Host
hostname := c.Param("hostname")
log.Println("TEST", hostname)
if err := DB.Where("hostname = ?", hostname).First(&host).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Record not found"})
}
c.JSON(http.StatusOK, host)
}
// CreateHost godoc
// @Summary Create a host
// @Description Create a host
// @Tags Hosts
// @Accept json
// @Produce json
// @Param host body models.CreateHostInput true "The host to create"
// @Success 200 {object} models.CreateHostInput
// @Router /hosts/create [post]
func CreateHost(c *gin.Context) {
var input models.CreateHostInput
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
host := models.Host{Hostname: input.Hostname}
result := DB.Create(&host)
if errors.Is(result.Error, gorm.ErrDuplicatedKey) {
c.JSON(http.StatusBadRequest, gin.H{"error": "Hostname already exists"})
return
}
c.JSON(http.StatusOK, input)
}
func main() {
cfg, err := ini.Load("config.ini")
if err != nil {
log.Fatal("Fail to read file: ", err)
}
// Classic read of values, default section can be represented as empty string
fmt.Println("App Mode: ", cfg.Section("").Key("app_mode").String())
fmt.Println("Database Type: ", cfg.Section("database").Key("type").String())
if strings.ToLower(cfg.Section("database").Key("type").String()) == "postgres" {
fmt.Println("Database Host: ", cfg.Section("database").Key("host").String())
fmt.Println("Database Port: ", cfg.Section("database").Key("port").String())
fmt.Println("Database Username:", cfg.Section("database").Key("username").String())
fmt.Println("Database Name: ", cfg.Section("database").Key("db_name").String())
databaseConnectString := fmt.Sprintf(
"host=%s port=%s user=%s dbname=%s password=%s sslmode=disable",
cfg.Section("database").Key("host"),
cfg.Section("database").Key("port"),
cfg.Section("database").Key("user"),
cfg.Section("database").Key("db_name"),
cfg.Section("database").Key("password"),
)
log.Println(databaseConnectString)
DB, err = gorm.Open(postgres.Open(databaseConnectString), &gorm.Config{TranslateError: true})
if err != nil {
log.Fatal("Failed to connect to PostgreSQL DB")
}
} else if strings.ToLower(cfg.Section("database").Key("type").String()) == "sqlite" {
sqlite_path := cfg.Section("database").Key("path").String()
fmt.Println("sqlite DB Path: ", sqlite_path)
DB, err = gorm.Open(sqlite.Open(sqlite_path), &gorm.Config{TranslateError: true})
if err != nil {
log.Fatal("Failed to open sqlite DB")
}
}
log.Println("Successfully connected to database")
err = DB.AutoMigrate(&models.CPU{})
if err != nil {
log.Fatal("Failed to migrate CPU schema")
}
err = DB.AutoMigrate(&models.Memory{})
if err != nil {
log.Fatal("Failed to migrate Memory schema")
}
err = DB.AutoMigrate(&models.Host{})
if err != nil {
log.Fatal("Failed to migrate Host schema")
}
r := gin.Default()
docs.SwaggerInfo.BasePath = "/api/v1"
v1 := r.Group("/api/v1")
{
hosts := v1.Group("/hosts")
{
hosts.GET("/hosts", GetHosts)
hosts.GET("/get_host_by_hostname/:hostname", GetHostByHostname)
hosts.POST("/create", CreateHost)
}
}
r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerfiles.Handler))
err = r.Run(":8080")
if err != nil {
log.Fatal("Failed to start API")
}
}