filename:
assistant/server/scratchpad.go
branch:
main
back to repo
package server
import (
"net/http"
"strings"
"unicode/utf8"
"assistant/tools"
"assistant/util"
)
type scratchpadResponse struct {
Content string `json:"content"`
Error string `json:"error,omitempty"`
}
type scratchpadPutRequest struct {
Content string `json:"content"`
}
func (a *API) handleScratchpadGET(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if a == nil || strings.TrimSpace(a.ScratchpadPath) == "" {
_ = util.WriteJSON(w, http.StatusNotFound, scratchpadResponse{Error: "scratchpad not configured"})
return
}
text, err := tools.ReadScratchpadLocked(a.ScratchpadPath)
if err != nil {
_ = util.WriteJSON(w, http.StatusInternalServerError, scratchpadResponse{Error: err.Error()})
return
}
if !utf8.ValidString(text) {
_ = util.WriteJSON(w, http.StatusInternalServerError, scratchpadResponse{Error: "scratchpad is not valid UTF-8"})
return
}
_ = util.WriteJSON(w, http.StatusOK, scratchpadResponse{Content: text})
}
func (a *API) handleScratchpadPUT(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPut {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if a == nil || strings.TrimSpace(a.ScratchpadPath) == "" {
_ = util.WriteJSON(w, http.StatusNotFound, scratchpadResponse{Error: "scratchpad not configured"})
return
}
var body scratchpadPutRequest
if err := util.DecodeJSON(r.Body, 1<<20, &body); err != nil {
_ = util.WriteJSON(w, http.StatusBadRequest, scratchpadResponse{Error: "invalid JSON body"})
return
}
if !utf8.ValidString(body.Content) {
_ = util.WriteJSON(w, http.StatusBadRequest, scratchpadResponse{Error: "content must be valid UTF-8"})
return
}
if err := tools.WriteScratchpadLocked(a.ScratchpadPath, body.Content); err != nil {
_ = util.WriteJSON(w, http.StatusInternalServerError, scratchpadResponse{Error: err.Error()})
return
}
_ = util.WriteJSON(w, http.StatusOK, scratchpadResponse{Content: body.Content})
}