Documentation
¶
Index ¶
- type Client
- type ErrorPayload
- type Meta
- type OptErrorPayload
- type Pagination
- type Reply
- func (r *Reply) AddHeader(key, value string) *Reply
- func (r *Reply) AddHeaders(headers map[string]string) *Reply
- func (r *Reply) CreatedBinary()
- func (r *Reply) CreatedHTML()
- func (r *Reply) CreatedJSON()
- func (r *Reply) CreatedStream()
- func (r *Reply) CreatedText()
- func (r *Reply) CreatedXML()
- func (r *Reply) Defer(funcs ...func()) *Reply
- func (r *Reply) DeleteHeader(key string) *Reply
- func (r *Reply) DeleteHeaders(keys []string) *Reply
- func (r *Reply) Error(code, message string, optional ...OptErrorPayload) *Reply
- func (r *Reply) FailJSON(code ...int)
- func (r *Reply) FailXML(code ...int)
- func (r *Reply) GetHeader(key string) string
- func (r *Reply) GetHeaders(keys []string) []string
- func (r *Reply) NoContent()
- func (r *Reply) OkBinary()
- func (r *Reply) OkHTML()
- func (r *Reply) OkJSON()
- func (r *Reply) OkStream()
- func (r *Reply) OkText()
- func (r *Reply) OkXML()
- func (r *Reply) Paginate(limit, offset, total int) *Reply
- func (r *Reply) ReplyBinary(code int)
- func (r *Reply) ReplyHTML(code int)
- func (r *Reply) ReplyJSON(code int)
- func (r *Reply) ReplyStream(code int)
- func (r *Reply) ReplyText(code int)
- func (r *Reply) ReplyXML(code int)
- func (r *Reply) SetCookies(cookies ...http.Cookie) *Reply
- func (r *Reply) SetHeader(key, value string) *Reply
- func (r *Reply) SetHeaders(headers map[string]string) *Reply
- func (r *Reply) Success(data any) *Reply
- type ReplyEnvelope
- type Stream
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Client ¶
type Client struct {
Finalizer func(data any, meta Meta) // Runs before sending
Transformer func(data any, meta Meta) any // Transforms payload
CodeAliases map[string]int // Maps error codes to HTTP status
DefaultHeaders map[string]string // Default response headers
}
Client holds global config for Reply instances.
func NewClient ¶
Create a new client with given configuration.
Example:
var Client = reply.NewClient(reply.Client{
Finalizer: finalizer,
Transformer: transformer,
CodeAliases map[string]int{
"SERVER_ERROR": 500,
"BAD_REQUEST": 400,
},
DefaultHeaders map[string]string{
"Content-Type": "application/json",
},
})
type ErrorPayload ¶
type ErrorPayload struct {
Code string `json:"code" xml:"code"` // Machine-readable error code
Message string `json:"message" xml:"message"` // Human-readable message
Details string `json:"details,omitempty" xml:"details,omitempty"` // Optional debug details
Field string `json:"field,omitempty" xml:"field,omitempty"` // Field causing the error (if any)
}
ErrorPayload defines the error response body.
Example:
ErrorPayload{Code: "NOT_FOUND", Message: "User not found"}
type Meta ¶
type Meta struct {
Status string `json:"status" xml:"status"` // "SUCCESS" or "ERROR"
Info string `json:"information,omitempty" xml:"information,omitempty"` // Optional info message
Pagination *Pagination `json:"pagination,omitempty" xml:"pagination,omitempty"` // Pagination info if applicable
}
Meta contains reply metadata.
Example:
Meta{Status: "SUCCESS", Info: "Fetched 10 items"}
type OptErrorPayload ¶
type OptErrorPayload struct {
Details string `json:"details,omitempty" xml:"details,omitempty"` // Optional debug details
Field string `json:"field,omitempty" xml:"field,omitempty"` // Field causing the error (if any)
}
OptErrorPayload holds optional error fields for partial errors.
Example:
OptErrorPayload{Details: "Invalid email format", Field: "email"}
type Pagination ¶
type Pagination struct {
NextOffset int `json:"nextOffset,omitempty" xml:"nextOffset,omitempty"` // Offset for the next page
HasNext bool `json:"hasNext,omitempty" xml:"hasNext,omitempty"` // True if more results exist
}
Pagination holds pagination metadata, embedded in Meta when needed.
Example:
Pagination{NextOffset: 20, HasNext: true}
type Reply ¶
type Reply struct {
*ReplyEnvelope
Payload any // Internal transformed payload
// contains filtered or unexported fields
}
Reply is the main HTTP response helper with chained methods.
func (*Reply) AddHeader ¶
AddHeader appends a value to a response header. Unlike SetHeader, this allows multiple values for the same header key.
Example:
rp.AddHeader("Set-Cookie", "session=abc123")
func (*Reply) AddHeaders ¶
AddHeaders appends multiple values to response headers. Each key-value pair is added without replacing existing values.
Example:
rp.AddHeaders(map[string]string{
"X-Custom-Header": "value1",
"X-Debug-Info": "enabled",
})
func (*Reply) CreatedBinary ¶
func (r *Reply) CreatedBinary()
CreatedBinary is a shortcut for ReplyBinary with http.StatusCreated (201).
func (*Reply) CreatedHTML ¶
func (r *Reply) CreatedHTML()
CreatedHTML sends status 201 Created with HTML body.
func (*Reply) CreatedJSON ¶
func (r *Reply) CreatedJSON()
CreatedJSON sends status 201 Created with JSON body.
func (*Reply) CreatedStream ¶
func (r *Reply) CreatedStream()
CreatedStream sends status 201 Created with stream body.
func (*Reply) CreatedText ¶
func (r *Reply) CreatedText()
CreatedText sends status 201 Created with plain text body.
func (*Reply) CreatedXML ¶
func (r *Reply) CreatedXML()
CreatedXML sends status 201 Created with XML body.
func (*Reply) Defer ¶
Defer registers one or more functions to be executed before the response is sent. These functions are executed in the order they were registered. Useful for cleanup operations, logging, or committing/rolling back transactions.
Example:
rp.Defer(func() { tx.Rollback() })
rp.Defer(func() { log.Println("Response sent") })
rp.Success(data).OkJSON() // deferred funcs execute before sending
func (*Reply) DeleteHeader ¶
DeleteHeader removes a response header by key.
Example:
rp.DeleteHeader("X-Powered-By")
func (*Reply) DeleteHeaders ¶
DeleteHeaders removes multiple response headers by their keys.
Example:
rp.DeleteHeaders([]string{"X-Powered-By", "X-API-Version"})
func (*Reply) Error ¶
func (r *Reply) Error(code, message string, optional ...OptErrorPayload) *Reply
Error sets reply status to "ERROR" and attaches an error payload.
func (*Reply) FailJSON ¶
FailJSON sends a JSON response with an error status. If code is provided, use it; otherwise, retrieve from CodeAliases or default to 500.
func (*Reply) FailXML ¶
FailXML sends a XML response with an error status. If code is provided, use it; otherwise, retrieve from CodeAliases or default to 500.
func (*Reply) GetHeader ¶
GetHeader retrieves the value of a response header by key. Returns an empty string if the header doesn't exist.
Example:
contentType := rp.GetHeader("Content-Type")
func (*Reply) GetHeaders ¶
GetHeaders retrieves multiple response header values by their keys. Returns a slice of values in the same order as the input keys. Empty strings are returned for headers that don't exist.
Example:
values := rp.GetHeaders([]string{"Content-Type", "X-API-Version"})
func (*Reply) NoContent ¶
func (r *Reply) NoContent()
NoContent sends no content response with status 204
Example:
rp.NoContent()
func (*Reply) OkBinary ¶
func (r *Reply) OkBinary()
OkBinary is a shortcut for ReplyBinary with http.StatusOK (200).
func (*Reply) OkHTML ¶
func (r *Reply) OkHTML()
OkHTML is a shortcut for ReplyHTML with status 200 OK.
func (*Reply) OkJSON ¶
func (r *Reply) OkJSON()
OkJSON is a shortcut for ReplyJSON with status 200 OK.
func (*Reply) OkStream ¶
func (r *Reply) OkStream()
OkStream is a shortcut for ReplyStream with status 200 OK.
func (*Reply) OkText ¶
func (r *Reply) OkText()
OkText is a shortcut for ReplyText with status 200 OK.
func (*Reply) Paginate ¶ added in v1.0.0
Create pagianate information in meta data.
Example:
rp.Success(datas).Paginate(limit, offset, len(datas)).OkJSON()
func (*Reply) ReplyBinary ¶
ReplyBinary sends a binary response using the adapter's BinarySender. If Data is not []byte, it logs an error and sends an empty body.
Example:
rp.Success(imageData).OkBinary()
func (*Reply) ReplyHTML ¶
ReplyHTML sends an HTML string response with the specified status code. The Data in *Reply must be a string; if not, it will be treated as an empty string and an error will be logged. The string is automatically escaped before sending.
Example:
rp.Success("<p>Hello & welcome!</p>").ReplyHTML(http.StatusOK) // -> <p>Hello & welcome!</p>
func (*Reply) ReplyJSON ¶
ReplyJSON sends a JSON-formatted response with the specified status code. The Payload in *Reply will be automatically encoded.
Example:
rp.Success(Data{Msg: "ok"}).ReplyJSON(http.StatusOK) // -> {"msg":"ok"}
func (*Reply) ReplyStream ¶
ReplyStream sends a streaming response with the specified status code. Data must be of type Stream; otherwise, logs an error and sends an empty stream.
Example:
rp.Success(reply.Stream{Data: file, ContentType: "image/png"}).
ReplyStream(http.StatusOK) // streams the file as PNG
func (*Reply) ReplyText ¶
ReplyText sends a plain text response with the specified status code. Data must be a string; if not, logs an error and sends empty string.
Example:
rp.Success("Hello world!").ReplyText(http.StatusOK) // -> Hello world!
func (*Reply) ReplyXML ¶
ReplyXML sends an XML-formatted response with the specified status code. Payload will be marshaled to XML automatically.
Example:
rp.Success(User{ID: 1, Name: "Chesta"}).ReplyXML(http.StatusOK)
// -> <User><ID>1</ID><Name>Chesta</Name></User>
func (*Reply) SetCookies ¶
SetCookies adds one or more HTTP cookies to the response headers. Each cookie is converted to its string representation and added to the Set-Cookie header. Empty cookie strings are skipped.
Example:
rp.SetCookies(
http.Cookie{Name: "access_token", Value: accessToken},
http.Cookie{Name: "refresh_token", Value: refreshToken},
)
func (*Reply) SetHeader ¶
SetHeader sets a single response header, replacing any existing values. Use this when you want to ensure only one value exists for a header.
Example:
rp.SetHeader("Content-Type", "application/json")
func (*Reply) SetHeaders ¶
SetHeaders sets multiple response headers at once, replacing any existing values. Each key-value pair in the map will replace existing headers with the same key.
Example:
rp.SetHeaders(map[string]string{
"X-API-Version": "v2.0",
"Cache-Control": "no-cache",
})
type ReplyEnvelope ¶
type ReplyEnvelope struct {
Meta Meta `json:"meta" xml:"meta"` // Metadata section
Data any `json:"data" xml:"data"` // Payload data
}
ReplyEnvelope is the standard API response envelope.
Example:
ReplyEnvelope{Meta: Meta{Status: "SUCCESS"}, Data: user}