mirror of
https://github.com/akyaiy/GoSally-mvp.git
synced 2026-01-06 23:12:25 +00:00
Refactor handler methods to use instance methods for logging and error handling; add utility functions for UUID generation and JSON error responses.
This commit is contained in:
@@ -1,16 +1,23 @@
|
||||
package server_v1
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
|
||||
"GoSally-mvp/internal/config"
|
||||
"github.com/akyaiy/GoSally-mvp/internal/config"
|
||||
)
|
||||
|
||||
type ServerV1UtilsContract interface {
|
||||
extractDescriptionStatic(path string) (string, error)
|
||||
writeJSONError(status int, msg string)
|
||||
newUUID() string
|
||||
errNotFound()
|
||||
}
|
||||
|
||||
type ServerV1Contract interface {
|
||||
ServerV1UtilsContract
|
||||
|
||||
Handle(w http.ResponseWriter, r *http.Request)
|
||||
HandleList(w http.ResponseWriter, r *http.Request)
|
||||
|
||||
@@ -22,11 +29,11 @@ type HandlerV1 struct {
|
||||
w http.ResponseWriter
|
||||
r *http.Request
|
||||
|
||||
_log slog.Logger
|
||||
log slog.Logger
|
||||
|
||||
cfg *config.ConfigConf
|
||||
|
||||
allowedCmd *regexp.Regexp
|
||||
allowedCmd *regexp.Regexp
|
||||
listAllowedCmd *regexp.Regexp
|
||||
}
|
||||
|
||||
@@ -41,33 +48,3 @@ func (h *HandlerV1) HandleList(w http.ResponseWriter, r *http.Request) {
|
||||
h.r = r
|
||||
h._handleList()
|
||||
}
|
||||
|
||||
func errNotFound(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSONError(w, http.StatusBadRequest, "invalid request")
|
||||
_log.Error("HTTP request error", slog.String("remote", r.RemoteAddr), slog.String("method", r.Method), slog.String("url", r.URL.String()), slog.Int("status", http.StatusBadRequest))
|
||||
}
|
||||
|
||||
func writeJSONError(w http.ResponseWriter, status int, msg string) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
resp := map[string]interface{}{
|
||||
"status": "error",
|
||||
"error": msg,
|
||||
"code": status,
|
||||
}
|
||||
json.NewEncoder(w).Encode(resp)
|
||||
}
|
||||
|
||||
func extractDescriptionStatic(path string) (string, error) {
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
re := regexp.MustCompile(`---\s*#description\s*=\s*"([^"]+)"`)
|
||||
m := re.FindStringSubmatch(string(data))
|
||||
if len(m) <= 0 {
|
||||
return "", nil
|
||||
}
|
||||
return m[1], nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user