Add configuration and v1 server implementation; create handler methods for command execution and listing

This commit is contained in:
alex
2025-06-22 17:09:47 +03:00
parent c15e6c5b15
commit 27bda702bd
14 changed files with 10 additions and 8 deletions

17
v1/go.mod Normal file
View File

@@ -0,0 +1,17 @@
module github.com/akyaiy/GoSally-mvp/v1
go 1.24.4
require (
github.com/akyaiy/GoSally-mvp/internal/config v0.0.0-20250622140114-c15e6c5b1592
github.com/go-chi/chi/v5 v5.2.2
github.com/yuin/gopher-lua v1.1.1
)
require (
github.com/BurntSushi/toml v1.5.0 // indirect
github.com/ilyakaznacheev/cleanenv v1.5.0 // indirect
github.com/joho/godotenv v1.5.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 // indirect
)

21
v1/go.sum Normal file
View File

@@ -0,0 +1,21 @@
github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=
github.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
github.com/akyaiy/GoSally-mvp/internal/config v0.0.0-20250622085654-213db0b8c73b h1:RTHso+pWhmwWLFVMCMt6ZZ5oGGh0jbOAlN8vBnD2G8o=
github.com/akyaiy/GoSally-mvp/internal/config v0.0.0-20250622085654-213db0b8c73b/go.mod h1:VCJJWOEkisTU5IBIuNVEc2ahosMRnoVy/I/Dnf79KVM=
github.com/akyaiy/GoSally-mvp/internal/config v0.0.0-20250622140114-c15e6c5b1592 h1:V5QzqnFoDnOVpjxMb0ZsBAX5jDaPE6OEiHxZ40/pqxM=
github.com/akyaiy/GoSally-mvp/internal/config v0.0.0-20250622140114-c15e6c5b1592/go.mod h1:VCJJWOEkisTU5IBIuNVEc2ahosMRnoVy/I/Dnf79KVM=
github.com/go-chi/chi/v5 v5.2.2 h1:CMwsvRVTbXVytCk1Wd72Zy1LAsAh9GxMmSNWLHCG618=
github.com/go-chi/chi/v5 v5.2.2/go.mod h1:L2yAIGWB3H+phAw1NxKwWM+7eUH/lU8pOMm5hHcoops=
github.com/ilyakaznacheev/cleanenv v1.5.0 h1:0VNZXggJE2OYdXE87bfSSwGxeiGt9moSR2lOrsHHvr4=
github.com/ilyakaznacheev/cleanenv v1.5.0/go.mod h1:a5aDzaJrLCQZsazHol1w8InnDcOX0OColm64SlIi6gk=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/yuin/gopher-lua v1.1.1 h1:kYKnWBjvbNP4XLT3+bPEwAXJx262OhaHDWDVOPjL46M=
github.com/yuin/gopher-lua v1.1.1/go.mod h1:GBR0iDaNXjAgGg9zfCvksxSRnQx76gclCIb7kdAd1Pw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 h1:slmdOY3vp8a7KQbHkL+FLbvbkgMqmXojpFUO/jENuqQ=
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3/go.mod h1:oVgVk4OWVDi43qWBEyGhXgYxt7+ED4iYNpTngSLX2Iw=

92
v1/handle_com.go Normal file
View File

@@ -0,0 +1,92 @@
package v1
import (
"encoding/json"
"log/slog"
"net/http"
"os"
"path/filepath"
"github.com/go-chi/chi/v5"
lua "github.com/yuin/gopher-lua"
)
func (h *HandlerV1) _handle() {
uuid16 := h.newUUID()
h.log.Info("Received request", slog.String("version", "v1"), slog.String("connection-uuid", uuid16), slog.String("remote", h.r.RemoteAddr), slog.String("method", h.r.Method), slog.String("url", h.r.URL.String()))
cmd := chi.URLParam(h.r, "cmd")
if !h.allowedCmd.MatchString(string([]rune(cmd)[0])) {
h.writeJSONError(http.StatusBadRequest, "invalid command")
h.log.Error("HTTP request error", slog.String("connection-uuid", uuid16), slog.String("error", "invalid command"), slog.String("cmd", cmd), slog.Int("status", http.StatusBadRequest))
return
}
if !h.listAllowedCmd.MatchString(cmd) {
h.writeJSONError(http.StatusBadRequest, "invalid command")
h.log.Error("HTTP request error", slog.String("connection-uuid", uuid16), slog.String("error", "invalid command"), slog.String("cmd", cmd), slog.Int("status", http.StatusBadRequest))
return
}
scriptPath := filepath.Join(h.cfg.ComDir, cmd+".lua")
if _, err := os.Stat(scriptPath); err != nil {
h.writeJSONError(http.StatusNotFound, "command not found")
h.log.Error("HTTP request error", slog.String("connection-uuid", uuid16), slog.String("error", "command not found"), slog.String("cmd", cmd), slog.Int("status", http.StatusNotFound))
return
}
L := lua.NewState()
defer L.Close()
L.OpenLibs() // loads base, io, os, string, math, table, debug, package, coroutine, channel… :contentReference[oaicite:0]{index=0}
qt := h.r.URL.Query()
tbl := L.NewTable()
for k, v := range qt {
if len(v) > 0 {
L.SetField(tbl, k, lua.LString(v[0]))
}
}
L.SetGlobal("Params", tbl)
L.SetGlobal("Result", L.NewTable())
L.DoString(`
print = function() end
io.write = function(...) end
io.stdout = function() return nil end
io.stderr = function() return nil end
io.read = function(...) return nil end
`)
if err := L.DoFile(scriptPath); err != nil {
h.writeJSONError(http.StatusInternalServerError, "lua error: "+err.Error())
h.log.Error("Failed to execute lua script", slog.String("connection-uuid", uuid16), slog.String("error", err.Error()))
return
}
out := make(map[string]any)
if rt := L.GetGlobal("Result"); rt.Type() == lua.LTTable {
rt.(*lua.LTable).ForEach(func(k, v lua.LValue) {
switch v.Type() {
case lua.LTString:
out[k.String()] = v.String()
case lua.LTNumber:
out[k.String()] = float64(v.(lua.LNumber))
case lua.LTBool:
out[k.String()] = bool(v.(lua.LBool))
default:
out[k.String()] = v.String()
}
})
}
h.w.Header().Set("Content-Type", "application/json")
json.NewEncoder(h.w).Encode(out)
switch out["status"] {
case "error":
h.log.Info("Command executed with error", slog.String("connection-uuid", uuid16), slog.String("cmd", cmd), slog.Any("result", out))
case "ok":
h.log.Info("Command executed successfully", slog.String("connection-uuid", uuid16), slog.String("cmd", cmd), slog.Any("result", out))
default:
h.log.Info("Command executed and returned an unknown status", slog.String("connection-uuid", uuid16), slog.String("cmd", cmd), slog.Any("result", out))
}
h.log.Info("Session completed", slog.String("connection-uuid", uuid16), slog.String("remote", h.r.RemoteAddr), slog.String("method", h.r.Method), slog.String("url", h.r.URL.String()))
}

55
v1/handle_list.go Normal file
View File

@@ -0,0 +1,55 @@
package v1
import (
"encoding/json"
"log/slog"
"net/http"
"os"
"path/filepath"
_ "github.com/go-chi/chi/v5"
)
func (h *HandlerV1) _handleList() {
uuid16 := h.newUUID()
h.log.Info("Received request", slog.String("version", "v1"), slog.String("connection-uuid", uuid16), slog.String("remote", h.r.RemoteAddr), slog.String("method", h.r.Method), slog.String("url", h.r.URL.String()))
type ComMeta struct {
Description string
}
var (
files []os.DirEntry
err error
com ComMeta
commands = make(map[string]ComMeta)
)
if files, err = os.ReadDir(h.cfg.ComDir); err != nil {
h.writeJSONError(http.StatusInternalServerError, "failed to read commands directory: "+err.Error())
h.log.Error("Failed to read commands directory", slog.String("error", err.Error()))
return
}
for _, file := range files {
if file.IsDir() || filepath.Ext(file.Name()) != ".lua" {
continue
}
cmdName := file.Name()[:len(file.Name())-4] // remove .lua extension
if !h.allowedCmd.MatchString(string([]rune(cmdName)[0])) {
continue
}
if !h.listAllowedCmd.MatchString(cmdName) {
continue
}
if com.Description, err = h.extractDescriptionStatic(filepath.Join(h.cfg.ComDir, file.Name())); err != nil {
h.writeJSONError(http.StatusInternalServerError, "failed to read command: "+err.Error())
h.log.Error("Failed to read command", slog.String("error", err.Error()))
return
}
if com.Description == "" {
com.Description = "description missing"
}
commands[cmdName] = ComMeta{Description: com.Description}
}
json.NewEncoder(h.w).Encode(commands)
h.log.Info("Command executed successfully", slog.String("connection-uuid", uuid16))
h.log.Info("Session completed", slog.String("connection-uuid", uuid16), slog.String("remote", h.r.RemoteAddr), slog.String("method", h.r.Method), slog.String("url", h.r.URL.String()))
}

56
v1/server.go Normal file
View File

@@ -0,0 +1,56 @@
package v1
import (
"log/slog"
"net/http"
"regexp"
"github.com/akyaiy/GoSally-mvp/internal/config"
)
type ServerV1UtilsContract interface {
extractDescriptionStatic(path string) (string, error)
writeJSONError(status int, msg string)
newUUID() string
_errNotFound()
ErrNotFound(w http.ResponseWriter, r *http.Request)
}
type ServerV1Contract interface {
ServerV1UtilsContract
Handle(w http.ResponseWriter, r *http.Request)
HandleList(w http.ResponseWriter, r *http.Request)
_handle()
_handleList()
}
type HandlerV1 struct {
w http.ResponseWriter
r *http.Request
log slog.Logger
cfg *config.ConfigConf
allowedCmd *regexp.Regexp
listAllowedCmd *regexp.Regexp
}
func InitV1Server(o *HandlerV1) *HandlerV1 {
return o
}
func (h *HandlerV1) Handle(w http.ResponseWriter, r *http.Request) {
h.w = w
h.r = r
h._handle()
}
func (h *HandlerV1) HandleList(w http.ResponseWriter, r *http.Request) {
h.w = w
h.r = r
h._handleList()
}

57
v1/utils.go Normal file
View File

@@ -0,0 +1,57 @@
package v1
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"log/slog"
"net/http"
"os"
"regexp"
)
func (h *HandlerV1) ErrNotFound(w http.ResponseWriter, r *http.Request) {
h.w = w
h.r = r
h._errNotFound()
}
func (h *HandlerV1) newUUID() string {
bytes := make([]byte, 16)
_, err := rand.Read(bytes)
if err != nil {
h.log.Error("Failed to generate UUID", slog.String("error", err.Error()))
return ""
}
return hex.EncodeToString(bytes)
}
func (h *HandlerV1) _errNotFound() {
h.writeJSONError(http.StatusBadRequest, "invalid request")
h.log.Error("HTTP request error", slog.String("remote", h.r.RemoteAddr), slog.String("method", h.r.Method), slog.String("url", h.r.URL.String()), slog.Int("status", http.StatusBadRequest))
}
func (h *HandlerV1) writeJSONError(status int, msg string) {
h.w.Header().Set("Content-Type", "application/json")
h.w.WriteHeader(status)
resp := map[string]interface{}{
"status": "error",
"error": msg,
"code": status,
}
json.NewEncoder(h.w).Encode(resp)
}
func (h *HandlerV1) 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
}