DEV Community

Cover image for Less verbose, better maintenance
Marcos Filho
Marcos Filho

Posted on • Edited on

2 2

Less verbose, better maintenance

All the codes that you will see in this post you can check here

In the last post we delivered the content to response in our controller but the code it's not too readable. In this post, we will refact the code to be more readable and easy to deliver our content.

Inside cmd/http folder we will create a new folder called helper. This package will group functions to help the http layer to deal with request and response that will be used by any other handler in our project.

First of all, lets refact our book handler in cmd/http/book.go and see how our getAll will be

func (h *BookHandler) getAll(w http.ResponseWriter, r *http.Request) {
    if results, err := h.bookService.FindAll(); err != nil {
        helper.HandleError(w, err)
    } else {
        if results != nil && len(*results) > 0 {
            helper.JsonResponse(w, results, http.StatusOK)
        } else {
            helper.NoContent(w)
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Now the helper will help us to deal with error and with the response data.

In the helper package we will create a response.go and will move the addDefaultHeaders and writeData presents in book handler to our response.go file.

3 - We will start to the more easy method here, the NoContent function.

//cmd/http/helper/response.go
//...
func NoContent(w http.ResponseWriter) {
    addDefaultHeaders(w)
    w.WriteHeader(http.StatusNoContent)
}
Enter fullscreen mode Exit fullscreen mode

We just will add the default headers and send a Header to No Content Status.

2 - We will write the json data to response

//cmd/http/helper/response.go
//...
func JsonResponse(w http.ResponseWriter, data interface{}, httpStatus int) {
    addDefaultHeaders(w)
    w.WriteHeader(httpStatus)
    writeData(w, data)
}
Enter fullscreen mode Exit fullscreen mode

Again, we just move the boilerplate code to write data to a new function in helper package.

1 - Now, we will refact our error method to improve the process.

//cmd/http/helper/response.go
//...
func HandleError(w http.ResponseWriter, err error) {
    addDefaultHeaders(w)
    httpError := DealWith(err)
    w.WriteHeader(httpError.Status)

    if httpError.Status != http.StatusNoContent {
        writeData(w, httpError)
    }
}
Enter fullscreen mode Exit fullscreen mode

look that we have a new method called DealWith this method will check if the error is a registered error or an unexpected error to our application.

At the moment we will create an error.go inside helper folder to create the DealWith method for our code works without any error.

//cmd/http/helper/error.go
//...
type HttpError struct {
    Status      int      `json:"-"`
    Description string   `json:"description,omitempty"`
    Messages    []string `json:"messages,omitempty"`
}

func DealWith(err error) HttpError {

    return HttpError{
        Status:      http.StatusInternalServerError,
        Description: "Internal error, please report to admin",
    }
}
Enter fullscreen mode Exit fullscreen mode

In the next post we will describe the DealWith method to know a better way to produce errors in http layer.

API Trace View

How I Cut 22.3 Seconds Off an API Call with Sentry 🕒

Struggling with slow API calls? Dan Mindru walks through how he used Sentry's new Trace View feature to shave off 22.3 seconds from an API call.

Get a practical walkthrough of how to identify bottlenecks, split tasks into multiple parallel tasks, identify slow AI model calls, and more.

Read more →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay