Categorygithub.com/generalledger/response
modulepackage
2.0.0+incompatible
Repository: https://github.com/generalledger/response.git
Documentation: pkg.go.dev

# README

General Ledger

MPL 2.0 Go Report Card Code Coverage Build Status

Response

Response is a no-frills standardized response body wrapper with some added utility to help manage writing to a http.ResponseWriter.

Output Interface

{
  "status_code": 200,
  "status_text": "OK",
  "error_details": "Invalid email",
  "result": {
    // ...
  }
}

Usage

func MyHandlerFunc(w http.ResponseWriter, r *http.Request) {
    resp := response.New(w)
    defer resp.Output()

    models, err := getModels()
    if err != nil {
        resp.SetResult(http.StatusInternalServerError, nil).
            WithErrorDetails(err.Error())
        return
    }

    resp.SetResult(http.StatusOK, models)
}

Testing

func TestPingSuccess(t *testing.T) {
    recorder := httptest.NewRecorder()
    req := httptest.NewRequest(http.MethodGet, "/ping", nil)
    PingHandlerFunc(recorder, req)

    assert.Equal(t,
        response.Response{
            StatusCode: 200,
            StatusText: "OK",
            Result:     "pong",
        },
        response.Parse(recorder.Result().Body),
    )
}

# Functions

New instantiates a new Response struct prepared with a 500 Status.
Parse converts a io.ReadCloser (the type of a http.Response.Body) into a Response struct.

# Structs

Response is a no-frills standardized response body wrapper with some added utility to help manage writing to a http.ResponseWriter.