responsehelper

package module
v1.1.16 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 7 Imported by: 9

README

Response Helper

This is a simple utility that helps to standardize api responses across the application.

Installation

go get github.com/aruncs31s/responsehelper
import "github.com/aruncs31s/responsehelper"
Usage

I suggest you that you include this in your handler constructor like the following

type Handler struct {
    responseHelper responsehelper.ResponseHelper
}
func NewHandler() *Handler {
    return &Handler{
        responseHelper: responsehelper.NewResponseHelper(),
    }
}

Then you can use it in your handler methods like the following

h.responseHelper.Success(c, data)
{
    "success": true,
    "data": {
    // response data here
    },
    "meta": "2025-10-01T00:00:00Z"
}
Example used with Gin framework
func (h *userHandler) Login(c *gin.Context) {
	var loginData dto.LoginRequest
	if err := c.ShouldBindJSON(&loginData); err != nil {
		h.responseHelper.BadRequest(c, utils.ErrBadRequest.Error(), utils.ErrDetailBadRequestJSONPayload.Error())
		return
	}

	token, err := h.userService.Login(loginData.Email, loginData.Password)
	if err != nil {
		reaction := utils.NewReaction(err)
		if strings.Contains(err.Error(), utils.ErrNotFound.Error()) {
			h.responseHelper.Unauthorized(c, utils.ErrEmailorPasswordEmpty.Error())
			return
		}
		h.responseHelper.InternalError(c, reaction.Reaction(), err)
		return
	}
	data := map[string]string{"token": token}
	
	h.responseHelper.Success(c, data)

Features

Comes with intellisense support for VSCode and other IDEs.

Available Response Methods
Success(c *gin.Context, data interface{})

Sends a 200 OK response with the provided data.

SuccessWithPagination(c *gin.Context, data interface{}, meta interface{})

Sends a 200 OK response with data and pagination metadata.

BadRequest(c *gin.Context, message string, details string)

Sends a 400 Bad Request response with custom error message and details.

Unauthorized(c *gin.Context, message string)

Sends a 401 Unauthorized response.

NotFound(c *gin.Context, message string)

Sends a 404 Not Found response.

Conflict(c *gin.Context, message string, err error)

Sends a 409 Conflict response for resource conflicts.

h.responseHelper.Conflict(c, "Resource conflict", err)

Response:

{
    "success": false,
    "error": {
        "code": 409,
        "status": "CONFLICT",
        "message": "Resource conflict",
        "details": "Error details here"
    }
}
AlreadyExists(c *gin.Context, resource string, err error)

Sends a 409 Conflict response indicating that a resource already exists. This is a convenience method for the common case where a resource creation fails because the resource already exists.

h.responseHelper.AlreadyExists(c, "User", err)

Response:

{
    "success": false,
    "error": {
        "code": 409,
        "status": "CONFLICT",
        "message": "User already exists",
        "details": "Error details here"
    }
}
InternalError(c *gin.Context, message string, err error)

Sends a 500 Internal Server Error response.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Sort added in v1.1.13

func Sort[T WithName](in []T) []T

func SortDesc added in v1.1.14

func SortDesc[T WithName](in []T) []T

Types

type FilterDropdown

type FilterDropdown struct {
	ID       int    `json:"id"`
	Name     string `json:"name"`
	ParentID int    `json:"parent_id,omitempty"`
}

type ListResponse

type ListResponse struct {
	Success    bool        `json:"success"`
	List       interface{} `json:"list"`
	Meta       interface{} `json:"meta,omitempty"`
	TotalCount int         `json:"total_count,omitempty"`
	Message    string      `json:"message,omitempty"`
	ReqUI      string      `json:"req_id,omitempty"`
}

type ResponseHelper

type ResponseHelper interface {
	// BadRequest sends a 400 Bad Request response
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - message: A brief message describing the error.
	//   - details: Additional details about the error.
	//
	// Example:
	//  responseHelper.BadRequest(c, "Invalid input", "The 'name' field is required.")
	//
	// Example Response Body:
	// {
	//	"success": false,
	//	"error": {
	//		"code":    400,
	//		"status":  "BAD_REQUEST",
	//		"message": "Invalid input",
	//		"details": "The 'name' field is required."
	//	}
	// }
	BadRequest(c *gin.Context, message string, details string)

	// AlreadyExists sends a 409 Conflict response indicating resource already exists
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - resource: The name of the resource that already exists.
	//   - err: The error that occurred.
	//
	// Example:
	//  responseHelper.AlreadyExists(c, "User", err)
	//
	// Example Response Body:
	// {
	//	"success": false,
	//	"error": {
	//		"code":    409,
	//		"status":  "CONFLICT",
	//		"message": "User already exists",
	//		"details": "Error details here"
	//	}
	// }
	AlreadyExists(c *gin.Context, resource string, err error)

	// Conflict sends a 409 Conflict response
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - message: A brief message describing the error.
	//   - err: The error that occurred.
	//
	// Example:
	//  h.responseHelper.Conflict(c, "Resource conflict", err)
	//
	// Example Response Body:
	// {
	//	"success": false,
	//	"error": {
	//		"code":    409,
	//		"status":  "CONFLICT",
	//		"message": "Resource conflict",
	//		"details": "Error details here"
	//	}
	// }
	Conflict(c *gin.Context, message string, err error)
	// NotFound sends a 404 Not Found response
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - message: A brief message describing the error.
	//
	// Example:
	//  h.responseHelper.NotFound(c, "Resource not found")
	//
	// Example Response Body:
	// {
	//	"success": false,
	//	"error": {
	//		"code":    404,
	//		"status":  "NOT_FOUND",
	//		"message": "Resource not found"
	//	}
	// }
	NotFound(c *gin.Context, message string)

	// Unauthorized sends a 401 Unauthorized response
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - message: A brief message describing the error.
	//
	// Example:
	// h.responseHelper.Unauthorized(c, "Unauthorized access")
	//
	// Example Response Body:
	// {
	//	"success": false,
	//	"error": {
	//		"code":    401,
	//		"status":  "UNAUTHORIZED",
	//		"message": "Unauthorized access"
	//	}
	// }
	Unauthorized(c *gin.Context, message string)
	// Forbidden sends a 403 Forbidden response
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - message: A brief message describing the error.
	//
	// Example:
	// h.responseHelper.Forbidden(c, "Forbidden access")
	//
	// Example Response Body:
	// {
	//	"success": false,
	//	"error": {
	//		"code":    403,
	//		"status":  "FORBIDDEN",
	//		"message": "This User does not have access to the resource"
	//	}
	// }
	Forbidden(c *gin.Context, message string)
	// InternalError sends a 500 Internal Server Error response
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - message: A brief message describing the error.
	//   - err: The error that occurred.
	//
	// Example:
	//  h.responseHelper.InternalError(c, "An unexpected error occurred", err)
	//
	// Example Response Body:
	// {
	//	"success": false,
	//	"error": {
	//		"code":    500,
	//		"status":  "INTERNAL_SERVER_ERROR",
	//		"message": "An unexpected error occurred",
	//		"details": "Error details here"
	//	}
	// }
	InternalError(c *gin.Context, message string, err error)

	// Success sends a 200 OK response
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - data: The data to include in the response.
	//
	// Example:
	//  h.responseHelper.Success(c, data)
	//
	// Example Response Body:
	// {
	//	"success": true,
	//	"data": {
	//		// response data here
	//	},
	//	"meta": "2023-01-01T00:00:00Z"
	// }
	Success(c *gin.Context, data interface{})
	List(
		c *gin.Context,
		data interface{},
		totalCount ...int,
	)

	// ListWithMessage sends a 200 OK response with a list of resources, a count, and a message
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - data: The list data to include in the response.
	//   - count: The total count of resources.
	//   - message: A brief message to include in the response.
	//
	// Example:
	//  responseHelper.ListWithMessage(c, users, 42, "Users retrieved successfully")
	//
	// Example Response Body:
	// {
	//	"success": true,
	//	"list": [
	//		// response data here
	//	],
	//	"meta": "2023-01-01T00:00:00Z",
	//	"total_count": 42,
	//	"message": "Users retrieved successfully"
	// }
	ListWithMessage(
		c *gin.Context,
		data interface{},
		count int,
		message string,
	)
	// SuccessWithPagination sends a 200 OK response with pagination metadata
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - data: The data to include in the response.
	//   - meta: The pagination metadata.
	//
	// Example:
	//  h.responseHelper.SuccessWithPagination(c, data, meta)
	//
	// Example Response Body:
	// {
	//	"success": true,
	//	"data": {
	//		// response data here
	//	},
	//	"pagination": {
	//		"currentPage": 3,
	//		"pageSize": 10,
	//		"totalPages": 3,
	//		"totalRecords": 27
	//	}
	// }
	SuccessWithPagination(c *gin.Context, data interface{}, meta interface{})

	// Extended version of the [Success] method that includes a custom message in the response
	SuccessWithMessage(c *gin.Context, data interface{}, message string)
	// Created sends a 201 Created response
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - data: The data to include in the response.
	//
	// Example:
	//  responseHelper.Created(c, data)
	//
	// Example Response Body:
	// {
	//	"success": true,
	//	"data": {
	//		// response data here
	//	},
	//	"meta": "2023-01-01T00:00:00Z"
	// }
	Created(c *gin.Context, data interface{})

	// Deleted sends a 204 No Content response
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - message: what you have deleted eg: qualification
	//
	// Example:
	//  responseHelper.Deleted(c, "qualification")
	//
	// Example Response Body:
	// {
	//	"success": true,
	//	"message": "qualification deleted successfully",
	//	"meta": "2023-01-01T00:00:00Z"
	// }
	Deleted(c *gin.Context, message string)

	// NoContent sends a 204 No Content response
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//
	// Example:
	//  responseHelper.NoContent(c)
	//
	// Example Response Body:
	// {
	//	"success": true,
	//	"data":    null,
	//	"meta":    "2023-01-01T00:00:00Z"
	// }
	NoContent(c *gin.Context)

	// SendDoc sends a 200 OK response with a file attachment
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - contentType: The MIME type of the document (e.g. "application/pdf", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet").
	//   - filename: The name of the file to be sent as an attachment.
	//   - documentBytes: The raw bytes of the document to send.
	//
	// Example:
	//  responseHelper.SendDoc(c, "application/pdf", "report.pdf", pdfBytes)
	//
	// Example Response Headers:
	// Content-Type: application/pdf
	// Content-Disposition: attachment; filename=report.pdf
	// Content-Length: <byte length>
	SendDoc(
		c *gin.Context,
		contentType string,
		filename string,
		documentBytes []byte,
	)

	// Ok sends a 200 OK response with a request ID and data
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - data: The data to include in the response.
	//
	// Example:
	//  responseHelper.Ok(c, data)
	//
	// Example Response Body:
	// {
	//	"req_id":  "abc123",
	//	"success": true,
	//	"data": {
	//		// response data here
	//	},
	//	"meta": "2023-01-01T00:00:00Z"
	// }
	Ok(c *gin.Context, data interface{})

	// Filters sends a 200 OK response with available filter and sort options
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - filters: The available filter options to include in the response.
	//   - sort: Optional variadic sort options to include in the response.
	//
	// Example:
	//  responseHelper.Filters(c, availableFilters, sortOptions)
	//
	// Example Response Body:
	// {
	//	"success": true,
	//	"available_filters": {
	//		// filter options here
	//	},
	//	"available_sort": [
	//		// sort options here
	//	],
	//	"meta": "2023-01-01T00:00:00Z"
	// }
	Filters(
		c *gin.Context,
		filters any,
		sort ...any,
	)

	// FilterDropdown sends a 200 OK response with structured dropdown filter and sort options
	//
	// Parameters:
	//   - c: The Gin context to send the response to.
	//   - filters: A slice of FilterDropdown items, each with an ID, Name, and optional ParentID.
	//   - sorts: Optional variadic sort options to include in the response.
	//
	// Example:
	//  responseHelper.FilterDropdown(c, []responseHelper.FilterDropdown{{ID: 1, Name: "Active"}}, sortOptions)
	//
	// Example Response Body:
	// {
	//	"success": true,
	//	"available_filters": [
	//		{"id": 1, "name": "Active"},
	//		{"id": 2, "name": "Inactive", "parent_id": 1}
	//	],
	//	"available_sorts": [
	//		// sort options here
	//	],
	//	"meta": "2023-01-01T00:00:00Z"
	// }
	FilterDropdown(c *gin.Context, filters []FilterDropdown, sorts ...any)
	// TODO: Document
	SuccessList(c *gin.Context, data interface{})
}

func NewResponseHelper

func NewResponseHelper() ResponseHelper

type WithName added in v1.1.13

type WithName interface {
	String() string
}

Jump to

Keyboard shortcuts

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