API/holochecker_api.go

70 lines
1.3 KiB
Go

package main
import (
"errors"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
)
func check(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{
"detail": "I'm alright, thank you",
})
}
func getAvatar(ctx *gin.Context) {
avatar_id := ctx.Param("id")
if _, err := os.Stat("avatars"); errors.Is(err, os.ErrNotExist) {
err := os.Mkdir("avatars", os.ModePerm)
if err != nil {
log.Println(err)
}
}
filepath := filepath.Join("avatars", avatar_id)
file, err := os.Open(filepath)
if err != nil {
ctx.AbortWithStatusJSON(http.StatusNotFound, gin.H{"detail": "File not found"})
return
}
defer file.Close()
fileInfo, err := file.Stat()
if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
fileSize := fileInfo.Size()
buffer := make([]byte, fileSize)
_, err = file.Read(buffer)
if err != nil {
ctx.AbortWithError(http.StatusInternalServerError, err)
return
}
ctx.Data(http.StatusOK, "image/jpg", buffer)
}
func main() {
router := gin.Default()
router.GET("/avatars/:id", getAvatar)
router.GET("/check", check)
host := os.Getenv("HOST")
port := os.Getenv("PORT")
if host == "" {
host = "0.0.0.0"
}
if port == "" {
port = "9030"
}
server := host + ":" + port
fmt.Println("Running on", server)
router.Run(server)
}