sleeeeeeeep

This commit is contained in:
Jan Barfuss 2024-03-20 00:55:36 +01:00
parent 099a388e23
commit c3cd0efb11

View File

@ -2,27 +2,27 @@ package main
import ( import (
"net/http" "net/http"
"net/url"
"io"
"github.com/LeRoid-hub/Mensa-API/blob/go/api/fetch.go"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func main() { func main() {
r := gin.Default() r := gin.Default()
r.GET("/ping", ping) r.GET("/fetch/:url", fetchRoute)
r.GET("/fetch", fetchRoute)
r.Run("localhost:8080") r.Run("localhost:8080")
} }
func fetchRoute(c *gin.Context) { func fetchRoute(c *gin.Context) {
url := c.Query("url") url := c.Param("url")
if url == "" { if url == "" {
c.JSON(http.StatusBadRequest, gin.H{ c.JSON(http.StatusBadRequest, gin.H{
"error": "url is required", "error": "url is required",
}) })
return return
} }
resp, err := fetch.Fetch(url) resp, err := Fetch(url)
if err != nil { if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{ c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(), "error": err.Error(),
@ -30,13 +30,26 @@ func fetchRoute(c *gin.Context) {
return return
} }
defer resp.Body.Close() defer resp.Body.Close()
c.JSON(http.StatusOK, gin.H{ d, err := io.ReadAll(resp.Body)
"status": resp.Status, if err != nil {
}) c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
d = string(d)
c.JSON(http.StatusOK, d)
} }
func ping(c *gin.Context) { func Fetch(path string) (*http.Response, error) {
c.JSON(http.StatusOK, gin.H{ baseurl := "https://www.imensa.de/"
"message": "pong", queryurl := baseurl + "/" + path
}) u, err := url.ParseRequestURI(queryurl)
if err != nil {
return nil, err
}
return http.Get(u.String())
} }