forgejo-release-proxy/internal/webservice/handlers.go

78 lines
2.1 KiB
Go
Raw Normal View History

2024-08-03 16:29:19 +02:00
/*
Copyright © 2024 Laura Kalb <dev@lauka.net>
The code of this project is available under the MIT license. See the LICENSE file for more info.
*/
package webservice
import (
"encoding/json"
"io"
"log"
"net/http"
)
func codeLilaNetworkReleases(w http.ResponseWriter, r *http.Request) {
namespace := r.URL.Query().Get("namespace")
requestIp := r.Header.Get("X-Forwarded-For")
userAgent := r.Header.Get("User-Agent")
var releaseInfo forgejoRepoReleaseApiResponse
if requestIp == "" {
requestIp = r.RemoteAddr
}
enableCors(&w)
if namespace == "" {
http.Error(w, "400 Bad Request", http.StatusBadRequest)
return
}
// Target website URL
targetURL := "https://code.lila.network/api/v1/repos/" + namespace + "/releases/latest"
// Make the request to the target website
resp, err := http.Get(targetURL)
if err != nil {
log.Printf("Error fetching data from target website: %v", err)
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
log.Printf("code.lila.network returned non-200 response: %v. Request-IP: %v, User-Agent: %v", resp.Status, requestIp, userAgent)
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
}
// Read the response body
body, err := io.ReadAll(resp.Body)
if err != nil {
log.Printf("Error reading response body: %v", err)
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
}
err = json.Unmarshal(body, &releaseInfo)
if err != nil {
log.Printf("Error reading response body: %v", err)
http.Error(w, "500 Internal Server Error", http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(releaseInfo.TagName))
}
func Run() error {
log.Println("starting webserver, listening on 0.0.0.0:8080")
http.HandleFunc("/__version__", baseVersion)
http.HandleFunc("/__heartbeat__", baseHeartbeat)
http.HandleFunc("/__lbheartbeat__", baseHeartbeat)
http.HandleFunc("/api/v1/code.lila.network/releases", codeLilaNetworkReleases)
return http.ListenAndServe(":8080", nil)
}