hash-of-wisdom/internal/protocol/responses.go

77 lines
1.9 KiB
Go
Raw Normal View History

package protocol
import (
"encoding/json"
"io"
"hash-of-wisdom/internal/pow/challenge"
"hash-of-wisdom/internal/quotes"
)
// ChallengeResponse represents a challenge response
type ChallengeResponse struct {
Challenge *challenge.Challenge
}
// Decode reads a challenge response from the payload stream
func (r *ChallengeResponse) Decode(stream io.Reader) error {
if stream == nil {
return io.EOF
}
// Parse JSON directly from stream
decoder := json.NewDecoder(stream)
return decoder.Decode(&r.Challenge)
}
// SolutionResponse represents a successful solution response (contains quote)
type SolutionResponse struct {
Quote *quotes.Quote
}
// Decode reads a solution response from the payload stream
func (r *SolutionResponse) Decode(stream io.Reader) error {
if stream == nil {
return io.EOF
}
// Parse JSON directly from stream
decoder := json.NewDecoder(stream)
return decoder.Decode(&r.Quote)
}
// ErrorResponse represents an error response
type ErrorResponse struct {
Code string `json:"code"`
Message string `json:"message"`
RetryAfter int `json:"retry_after,omitempty"`
Details map[string]string `json:"details,omitempty"`
}
// Decode reads an error response from the payload stream
func (r *ErrorResponse) Decode(stream io.Reader) error {
if stream == nil {
return io.EOF
}
// Parse JSON directly from stream
decoder := json.NewDecoder(stream)
return decoder.Decode(r)
}
// Encode writes the challenge response to the writer
func (r *ChallengeResponse) Encode(w io.Writer) error {
return encode(w, ChallengeResponseType, r.Challenge)
}
// Encode writes the solution response to the writer
func (r *SolutionResponse) Encode(w io.Writer) error {
return encode(w, QuoteResponseType, r.Quote)
}
// Encode writes the error response to the writer
func (r *ErrorResponse) Encode(w io.Writer) error {
return encode(w, ErrorResponseType, r)
}