reply

package
v1.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 8, 2025 License: MIT Imports: 8 Imported by: 0

Documentation

Index

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

func NewClient(config Client) *Client

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",
	},
})

func (*Client) New

func (c *Client) New(adapter adapter.Adapter) *Reply

Create a new reply.

Example:

rp := Client.New(nethttpadapter.Adapt(w))
// ...
rp.Success(datas).Paginate(limit, offset, len(datas)).OkJSON()

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

func (r *Reply) AddHeader(key, value string) *Reply

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

func (r *Reply) AddHeaders(headers map[string]string) *Reply

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

func (r *Reply) Defer(funcs ...func()) *Reply

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

func (r *Reply) DeleteHeader(key string) *Reply

DeleteHeader removes a response header by key.

Example:

rp.DeleteHeader("X-Powered-By")

func (*Reply) DeleteHeaders

func (r *Reply) DeleteHeaders(keys []string) *Reply

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

func (r *Reply) FailJSON(code ...int)

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

func (r *Reply) FailXML(code ...int)

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

func (r *Reply) GetHeader(key string) string

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

func (r *Reply) GetHeaders(keys []string) []string

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) OkXML

func (r *Reply) OkXML()

OkXML is a shortcut for ReplyXML with status 200 OK.

func (*Reply) Paginate added in v1.0.0

func (r *Reply) Paginate(limit, offset, total int) *Reply

Create pagianate information in meta data.

Example:

rp.Success(datas).Paginate(limit, offset, len(datas)).OkJSON()

func (*Reply) ReplyBinary

func (r *Reply) ReplyBinary(code int)

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

func (r *Reply) ReplyHTML(code int)

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 &amp; welcome!</p>

func (*Reply) ReplyJSON

func (r *Reply) ReplyJSON(code int)

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

func (r *Reply) ReplyStream(code int)

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

func (r *Reply) ReplyText(code int)

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

func (r *Reply) ReplyXML(code int)

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

func (r *Reply) SetCookies(cookies ...http.Cookie) *Reply

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

func (r *Reply) SetHeader(key, value string) *Reply

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

func (r *Reply) SetHeaders(headers map[string]string) *Reply

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",
})

func (*Reply) Success

func (r *Reply) Success(data any) *Reply

Success marks the reply as successful and attaches data.

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}

type Stream

type Stream struct {
	Data        io.Reader // Stream source
	ContentType string    // MIME type of the stream
}

Stream enables streaming responses (files, SSE, etc.).

Example:

Stream{Data: fileReader, ContentType: "video/mp4"}

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL