Add web product Phase 1 skeleton
This commit is contained in:
@@ -0,0 +1,58 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"ai-workflow-skill/internal/store"
|
||||
)
|
||||
|
||||
type errorEnvelope struct {
|
||||
Error errorPayload `json:"error"`
|
||||
}
|
||||
|
||||
type errorPayload struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetIndent("", " ")
|
||||
_ = enc.Encode(payload)
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, err error) {
|
||||
status, code := classifyError(err)
|
||||
writeJSON(w, status, errorEnvelope{
|
||||
Error: errorPayload{
|
||||
Code: code,
|
||||
Message: errorMessage(err),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func classifyError(err error) (int, string) {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrInvalidInput):
|
||||
return http.StatusBadRequest, "invalid_input"
|
||||
case errors.Is(err, store.ErrRunNotFound), errors.Is(err, store.ErrTaskNotFound), errors.Is(err, store.ErrThreadNotFound):
|
||||
return http.StatusNotFound, "not_found"
|
||||
case errors.Is(err, store.ErrInvalidState):
|
||||
return http.StatusConflict, "invalid_state"
|
||||
default:
|
||||
return http.StatusInternalServerError, "internal_error"
|
||||
}
|
||||
}
|
||||
|
||||
func errorMessage(err error) string {
|
||||
if err == nil {
|
||||
return "unknown error"
|
||||
}
|
||||
return fmt.Sprintf("%v", err)
|
||||
}
|
||||
Reference in New Issue
Block a user