Backend: Added basic endpoint with parameter gathering. Added sendResponse and GetFunctionName

This commit is contained in:
Yohan Boujon 2025-05-01 18:21:21 +02:00
parent e47db359db
commit 2f896195d5
3 changed files with 26 additions and 3 deletions

View file

@ -5,6 +5,12 @@ import (
"net/http"
)
func handlePictureRequest(w http.ResponseWriter, r *http.Request) {
util.Logformat(util.INFO, "Calling 'handlePictureRequest' with '%s'\n", r.Method)
func getphoto(w http.ResponseWriter, r *http.Request) {
idStr := r.URL.Query().Get("id")
if idStr == "" {
util.Logformat(util.ERROR, "%s: Missing 'id' parameter.", util.GetFunctionName())
http.Error(w, "Missing or invalid parameters : id", http.StatusBadRequest)
} else {
sendResponse(w, 0)
}
}

View file

@ -2,13 +2,14 @@ package server
import (
"backend/util"
"encoding/json"
"net/http"
"strconv"
)
func Start(port int64) {
// Creating endpoints
http.HandleFunc("/hello/", wrapHeader(handlePictureRequest))
http.HandleFunc("/getphoto", wrapHeader(getphoto))
util.Logformat(util.INFO, "Starting server on port %d...\n", port)
if err := http.ListenAndServe(":"+strconv.FormatInt(port, 10), nil); err != nil {
@ -17,6 +18,15 @@ func Start(port int64) {
}
}
func sendResponse(w http.ResponseWriter, r any) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(r); err != nil {
util.Logformat(util.ERROR, "%s\n", err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// Not sure about that, might change it later... (added by Lemonochrme on 'yoboujon/automatic-management')
func wrapHeader(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {

View file

@ -2,9 +2,16 @@ package util
import (
"net/http"
"runtime"
"strings"
)
func GetFunctionName() string {
pc, _, _, _ := runtime.Caller(1)
f := runtime.FuncForPC(pc)
return strings.Split(strings.Split(f.Name(), "/")[1], ".")[1]
}
func HasSubURI(r *http.Request) (bool, string) {
url := strings.Split(r.URL.Path, "/")
return (len(url[2]) > 0), url[2]