Mensa-API/api/server.go

56 lines
916 B
Go
Raw Normal View History

2024-03-19 22:56:55 +00:00
package main
import (
"net/http"
2024-03-19 23:55:36 +00:00
"net/url"
"io"
2024-03-19 22:56:55 +00:00
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
2024-03-19 23:55:36 +00:00
r.GET("/fetch/:url", fetchRoute)
2024-03-19 22:56:55 +00:00
r.Run("localhost:8080")
}
func fetchRoute(c *gin.Context) {
2024-03-19 23:55:36 +00:00
url := c.Param("url")
2024-03-19 22:56:55 +00:00
if url == "" {
c.JSON(http.StatusBadRequest, gin.H{
"error": "url is required",
})
return
}
2024-03-19 23:55:36 +00:00
resp, err := Fetch(url)
2024-03-19 22:56:55 +00:00
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
defer resp.Body.Close()
2024-03-19 23:55:36 +00:00
d, err := io.ReadAll(resp.Body)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": err.Error(),
})
return
}
d = string(d)
c.JSON(http.StatusOK, d)
2024-03-19 22:56:55 +00:00
}
2024-03-19 23:55:36 +00:00
func Fetch(path string) (*http.Response, error) {
baseurl := "https://www.imensa.de/"
queryurl := baseurl + "/" + path
u, err := url.ParseRequestURI(queryurl)
if err != nil {
return nil, err
}
return http.Get(u.String())
2024-03-19 22:56:55 +00:00
}