Skip to content

vinyguedess/gorilla-easy-handler

Repository files navigation

CIBuild Maintainability Test Coverage

Gorilla Easy Handler

Facilitator for handling gorilla/mux requests.

Introduction

Basically http.ResponseWriter and http.Request are encapsulated in two structs: geh.Response and geh.Request. Both come with methods that facilitate the implementation and don't require developer to worry about some things.

Getting started

First, we create a basic Gorrila/Mux API.

func HomeHandler(
	request geh.Request, 
	response geh.Response,
	arguments ...interface{},
) {
	printSomething := arguments[0].(func (string))
	printSomething("print something")

	geh.Status(http.StatusOk).
		Json(map[string]interface{}{
            "hello": "I",
            "am": "okay"
        })
}

func main() {
	func printSomething(something string) {
		print(something)
	}

    r := geh.NewRouter("API Name", "API Version")
    r.HandleFunc(
		http.MethodGet, // HTTP Method
		"/", // Endpoint
		geh.Handler(HomeHandler, printSomething), // Handler
		geh.DocEndpoint{ // Documentation to be rendered by swagger
			Summary: "Home",
		},
	)

	http.ListenAndServe(":8080", r.GetMuxRouter())
}

Documentation

Endpoints documentation is generated by Swagger. It's accessed through the endpoint /docs.

Request

GetMethod

Returns HTTP Method used in current request.

GetURI

Returns current URI.

GetURL

Returns current URL.

GetParams

Get a URL param value. If not found return an empty string.

func HomeHandler(request geh.Request, response geh.Response) {
	response.Text(fmt.sprintf(
		"My ID is %s", 
		request.GetParams("id"),
    ))
}

GetQueryString

Get query string from URL. If not found return an empty string.

func HomeHandler(request geh.Request, geh.Response) {
	response.Text(fmt.sprintf(
	    "My ID in query string is %s",
	    request.GetQueryString("id")
    ))
}

GetHeader

Get a header value. If not found return an empty string.

func HomeHandler(request geh.Request, geh.Response) {
	response.Text(fmt.sprintf(
	    "My Content-Type is %s",
	    request.GetHeader("Content-Type")
    ))
}