package app import ( "encoding/json" "net/http" ) var apiEndpointHandlers = map[string]func(w http.ResponseWriter, r *http.Request){ "me": httpHandleAPIMe, } func httpBaseHandleAPI(w http.ResponseWriter, r *http.Request, path []string) bool { if path[0] != "api" || len(path) < 2 { return false } handler := apiEndpointHandlers[path[1]] if handler == nil { return false } handler(w, r) return true } func httpHandleJSONError(w http.ResponseWriter, err error) { w.Header().Add("Content-Type", "application/json") statusCode := getErrorHttpStatusCode(err) w.WriteHeader(statusCode) w.Write([]byte("{\"success\": false}")) } func httpHandleJSON(w http.ResponseWriter, data any) { out, err := json.Marshal(data) if err != nil { httpHandleJSONError(w, err) return } w.Header().Add("Content-Type", "application/json") w.WriteHeader(http.StatusOK) w.Write(out) } func httpHandleAPIMe(w http.ResponseWriter, r *http.Request) { clientID := getUserClientID(r) user, err := getCurrentUserFromSession(r) if err == nil { httpHandleJSON(w, map[string]any{ "success": true, "client_id": clientID, "user_id": user.ID, "user_name": user.Username, "user_created_at": user.CreatedAt, }) return } httpHandleJSON(w, map[string]any{ "success": true, "client_id": clientID, "user_id": nil, "user_name": nil, "user_created_at": nil, }) }