respond

package
v1.0.10 Latest Latest
Warning

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

Go to latest
Published: Aug 22, 2022 License: Apache-2.0, Apache-2.0 Imports: 5 Imported by: 0

README

Respond

Package respond provides idiomatic way for API responses.

  • respond.JSON - for success responses.
  • respond.JSONError - for fail responses.
  • respond.SetJSONErrorResponse - useful for handling errors differently, define custom response.

respond.JSONError response depends on go-core/errors pkg for HTTP status and Msg message.

Feel free to add new functions or improve the existing code.

Install

go get github.com/iconimpact/go-core/respond

Usage and Examples


// handle errors differently, define custom response.
errorRsp := func(err error) interface{} {
	var status int
	var errMsg string

	// set custom app err Message
	appErr, ok := err.(*errors.Error)
	if !ok {
		status = http.StatusInternalServerError
		errMsg = "Internal Server Error"
	} else {
		status = errors.ToHTTPStatus(appErr)
		errMsg = errors.ToHTTPResponse(appErr)
	}

	rsp := struct {
		Msg    string `json:"msg"`
		Status int    `json:"status"`
	}{
		Msg:    errMsg,
		Status: status,
	}

	return rsp
}
respond.SetJSONErrorResponse(errorRsp)

// usage in handler
func handleRoute(w http.ResponseWriter, r *http.Request) {

	data, err := loadFromDB()
	if err != nil {

	    // respond with an error
		respond.JSONError(w, logger, errors.E(err, errors.NotFound, "Data not found"))
		return // always return after responding

	}

	// respond with OK, and the data
	respond.JSON(w, logger, http.StatusOK, data)

}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func JSON

func JSON(w http.ResponseWriter, l *zap.Logger, status int, v interface{})

JSON serializes the given struct as JSON into the response body. It also sets the Content-Type as "application/json" and X-Content-Type-Options as "nosniff". Logs the status and v if l is not nil.

func JSONError

func JSONError(w http.ResponseWriter, l *zap.Logger, err error)

JSONError returns an HTTP response as JSON message with status code base on app err Kind, Msg from app err HTTPMessage. Logs the error if l is not nil.

func SetJSONErrorResponse added in v1.0.2

func SetJSONErrorResponse(fn func(err error) interface{})

SetJSONErrorResponse useful for handling errors differently, define custom response.

Types

This section is empty.

Jump to

Keyboard shortcuts

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