Files
marqdo/plugins/web/internal/httpx/routes_artifact.go
T
cflmy 9331af78e2 release(2.8.0): 合入 CHANGELOG/README/发版说明/skills prove 任务;CI 链接指向 doc/releases
- CHANGELOG.md:v2.8.0 条目(中英双语);
- README.md:版本行 2.7.1→2.8.0 + 愿景第 6 条(知识可证明);
- doc/releases/v2.8.0.md:双语发版说明(亮点/用法/已知限制);
- skills/marqdo-dev/index.mq.md:新增 prove 任务(路径/目录模式/
  require_lean/json;参数用 + 行声明升参,check 与 narrative-ratio 通过);
- 设计文档 §12.5 标记已合入;发版链接统一指向 doc/releases/v2.8.0.md。
2026-11-18 10:29:26 +08:00

160 lines
4.3 KiB
Go
Executable File

package httpx
import (
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/marqdo/marqdo/plugins/web/internal/plugin"
"github.com/marqdo/marqdo/plugins/web/internal/session"
)
// artifactRoute is one Endpoint file registered by web.serve (ADR 0007).
type artifactRoute struct {
Method string
Path string
File string
Request string // json | form | none | query
Response string // json | text | html | sse
Auth string // role name or "" / "none" | "bearer"
}
func parseArtifactRoute(v any) artifactRoute {
m, _ := v.(map[string]any)
return artifactRoute{
Method: strings.ToUpper(strOpt(m, "method", "GET")),
Path: strOpt(m, "path", ""),
File: strOpt(m, "file", ""),
Request: strings.ToLower(strOpt(m, "request", "json")),
Response: strings.ToLower(strOpt(m, "response", "json")),
Auth: strOpt(m, "auth", ""),
}
}
func (st *state) mountArtifactRoutes(mux routeRegistrar) {
for _, key := range sortedKeys(st.artifactRoutes) {
cfg := parseArtifactRoute(st.artifactRoutes[key])
if cfg.File == "" || cfg.Path == "" {
continue
}
method := cfg.Method
if method == "" {
method = http.MethodGet
}
pattern := method + " " + goMuxPattern(cfg.Path)
routeCfg := cfg
mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
if r.Method != method {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
st.handleArtifact(w, r, routeCfg)
})
}
}
func (st *state) handleArtifact(w http.ResponseWriter, r *http.Request, route artifactRoute) {
if route.Auth != "" && !strings.EqualFold(route.Auth, "none") {
if strings.EqualFold(route.Auth, "bearer") || strings.EqualFold(route.Auth, "api_key") {
// Bearer / API-key auth is enforced inside the Endpoint `# main`
// (payload carries authorization / api_key). Do not require cookies.
} else {
cookie := r.Header.Get("Cookie")
user := session.UsernameFromCookie(cookie)
if user == "" {
jsonErr(w, http.StatusUnauthorized, "auth required")
return
}
role := session.RoleFromCookie(cookie)
if role != "" && role != route.Auth && role != "admin" && role != "superadmin" {
jsonErr(w, http.StatusForbidden, "forbidden")
return
}
}
}
payload := map[string]any{}
switch route.Request {
case "none":
payload = queryToMap(r.URL.RawQuery)
case "query":
payload = queryToMap(r.URL.RawQuery)
case "form":
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8<<20))
if err != nil {
jsonErr(w, http.StatusBadRequest, fmt.Sprintf("body: %v", err))
return
}
payload = formToMap(body)
default: // json
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8<<20))
if err != nil {
jsonErr(w, http.StatusBadRequest, fmt.Sprintf("body: %v", err))
return
}
q := queryToMap(r.URL.RawQuery)
if len(body) == 0 {
payload = q
} else {
var raw map[string]any
if err := json.Unmarshal(body, &raw); err != nil {
jsonErr(w, http.StatusBadRequest, fmt.Sprintf("json: %v", err))
return
}
if raw == nil {
payload = q
} else {
for k, v := range q {
if _, exists := raw[k]; !exists {
raw[k] = v
}
}
payload = raw
}
}
}
for _, name := range pathParamNames(route.Path) {
if v := r.PathValue(name); v != "" {
payload[name] = v
}
}
if auth := strings.TrimSpace(r.Header.Get("Authorization")); auth != "" {
if _, exists := payload["authorization"]; !exists {
payload["authorization"] = auth
}
}
if key := strings.TrimSpace(r.Header.Get("X-Api-Key")); key != "" {
if _, exists := payload["api_key"]; !exists {
payload["api_key"] = key
}
}
value, err := plugin.RunArtifactAtRoot(route.File, payload, st.entryDir)
if err != nil {
jsonErr(w, http.StatusInternalServerError, err.Error())
return
}
switch route.Response {
case "text":
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, fmt.Sprint(value))
case "html", "text/html":
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
_, _ = io.WriteString(w, fmt.Sprint(value))
case "sse", "event-stream", "text/event-stream":
writeSSE(w, value)
default:
code, body, err := jsonWrapInvokeValue(value)
if err != nil {
jsonErr(w, code, err.Error())
return
}
writeJSON(w, code, body)
}
}