Categorygithub.com/mrz1836/go-api-router
modulepackage
0.8.3
Repository: https://github.com/mrz1836/go-api-router.git
Documentation: pkg.go.dev

# README

go-api-router

Lightweight API httprouter middleware: cors, logging, and standardized error handling.

Release Build Status Report codecov Go
Sponsor Donate


Table of Contents


Installation

go-api-router requires a supported release of Go.

go get -u github.com/mrz1836/go-api-router

Documentation

View the generated documentation

GoDoc

Features

  • Uses the fastest router: Julien Schmidt's httprouter
  • Uses gofr's uuid package to guarantee unique request ids
  • Uses MrZ's go-logger for either local or remote logging via Log Entries (Rapid7)
  • Uses MrZ's go-parameters for parsing any type of incoming parameter with ease
  • Optional: NewRelic support!
  • Added basic middleware support from Rileyr's middleware
  • Optional: JWT Authentication (middleware)
  • Added additional CORS functionality
  • Standardized error responses for API requests
  • Centralized logging on all requests (requesting user info & request time)
  • Custom response writer for Etag and cache support
  • GetClientIPAddress() safely detects IP addresses behind load balancers
  • GetParams() parses parameters only once
  • FilterMap() removes any confidential parameters from logs
  • ...and more!
Package Dependencies
Library Deployment

goreleaser for easy binary or library deployment to GitHub and can be installed via: brew install goreleaser.

The .goreleaser.yml file is used to configure goreleaser.

Use make release-snap to create a snapshot version of the release, and finally make release to ship to production.

Makefile Commands

View all makefile commands

make help

List of all current commands:

all                  Runs lint, test and vet
clean                Remove previous builds and any test cache data
clean-mods           Remove all the Go mod cache
coverage             Shows the test coverage
godocs               Sync the latest tag with GoDocs
help                 Show this help message
install              Install the application
install-go           Install the application (Using Native Go)
lint                 Run the golangci-lint application (install if not found)
release              Full production release (creates release in Github)
release              Runs common.release then runs godocs
release-snap         Test the full release (build binaries)
release-test         Full production test release (everything except deploy)
replace-version      Replaces the version in HTML/JS (pre-deploy)
run-examples         Runs all the examples
tag                  Generate a new tag and push (tag version=0.0.0)
tag-remove           Remove a tag if found (tag-remove version=0.0.0)
tag-update           Update an existing tag to current commit (tag-update version=0.0.0)
test                 Runs vet, lint and ALL tests
test-ci              Runs all tests via CI (exports coverage)
test-ci-no-race      Runs all tests via CI (no race) (exports coverage)
test-ci-short        Runs unit tests via CI (exports coverage)
test-short           Runs vet, lint and tests (excludes integration tests)
uninstall            Uninstall the application (and remove files)
update-linter        Update the golangci-lint package (macOS only)
vet                  Run the Go vet application

Examples & Tests

All unit tests and examples run via GitHub Actions and uses Go version 1.22.x. View the configuration file.

Run all tests (including integration tests)

make test

Run tests (excluding integration tests)

make test-short

Run the examples:

make run-examples

Benchmarks

Run the Go benchmarks:

make bench

Code Standards

Read more about this Go project's code standards.


Usage

View the examples

Basic implementation:

package main

import (
	"fmt"
	"net/http"

	"github.com/julienschmidt/httprouter"
	"github.com/mrz1836/go-api-router"
	"github.com/mrz1836/go-logger"
)

func main() {
	// Load the router & middleware
	router := apirouter.New()

	// Set the main index page (navigating to slash)
	router.HTTPRouter.GET("/", router.Request(index))

	// Serve the router!
	logger.Fatalln(http.ListenAndServe(":3000", router.HTTPRouter))
}

func index(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
	_, _ = fmt.Fprint(w, "This is a simple route example!")
}

Maintainers

MrZ
MrZ

Contributing

View the contributing guidelines and please follow the code of conduct.

How can I help?

All kinds of contributions are welcome :raised_hands:! The most basic way to show your support is to star :star2: the project, or to raise issues :speech_balloon:. You can also support this project by becoming a sponsor on GitHub :clap: or by making a bitcoin donation to ensure this journey continues indefinitely! :rocket:

Stars


License

License

# Packages

Package main shows examples using the API Router */.

# Functions

Check will check if the JWT is present and valid in the request and then extend the token.
ClearToken will remove the token from the response and request.
CreateToken will make the claims, and then make/sign the token.
ErrorFromRequest gives an error without a response writer using the request.
ErrorFromResponse generates a new error struct using CustomResponseWriter from LogRequest().
FilterMap will filter the parameters and not log parameters with sensitive data.
FindString returns the index of the first instance of needle in the array or -1 if it could not be found.
GetAuthToken gets the stored authentication token from the request.
GetClaims will return the current claims from the request.
GetClientIPAddress gets the client ip address.
GetCustomData gets the stored custom data.
GetIPFromRequest gets the stored ip from the request if found.
GetParams gets the params from the http request (parsed once on log request) Helper method for the parameters package.
GetRequestID gets the stored request id from the request.
GetTokenFromHeader will get the token value from the header.
GetTokenFromHeaderFromRequest will get the token value from the request.
GetTokenFromResponse will get the token value from the HTTP response.
JSONEncode will encode only the allowed fields of the models.
JSONEncodeHierarchy will execute JSONEncode for multiple nested objects.
New returns a router middleware configuration to use for all future requests.
NewStack will create an InternalStack struct.
NewWithNewRelic returns a router middleware configuration with NewRelic enabled.
NoCache is a simple piece of middleware that sets a number of HTTP headers to prevent a router (or subrouter) from being cached by an upstream proxy and/or client.
PermitParams will remove all keys that not allowed Helper method for the parameters package.
ReturnJSONEncode is a mixture of ReturnResponse and JSONEncode.
ReturnResponse helps return a status code and message to the end user.
SetAuthToken set the authentication token on the request.
SetCustomData set the custom data / user profile / permissions / etc.
SetOnRequest will set the value on the request with the given key.
SetTokenHeader will set the authentication token on the response and set a cookie.
SnakeCase takes a camelCaseWord and breaks it into a camel_case_word.
StandardHandlerToHandle converts a standard middleware to Julien handle version.
StandardHandlerToMiddleware converts a standard middleware to type Middleware.

# Constants

AuthorizationBearer is the second part of the auth header.
AuthorizationHeader is the auth header.
CookieName is for the secure cookie that also has the JWT token.
ErrCodeUnknown unknown error code (example).
Log formats for the request.
Log formats for the request.
Log formats for the request.
Log formats for the request.
StatusCodeUnknown unknown HTTP status code (example).

# Variables

ErrClaimsValidationFailed is when the claim's validation has failed.
ErrHeaderInvalid is when the header is missing or invalid.
ErrInvalidSessionID is when the session id is invalid or missing.
ErrInvalidUserID is when the user ID is invalid or missing.
ErrIssuerMismatch is when the issuer does not match the system issuer.
ErrJWTInvalid is when the JWT payload is invalid.

# Structs

APIError is the enriched error message for API related errors.
APIResponseWriter wraps the ResponseWriter and stores the status of the request.
Claims is our custom JWT claims.
InternalStack internal stack type.
Router is the configuration for the middleware service.

# Interfaces

LoggerInterface is the logger interface.
Stack is the interface for middleware.

# Type aliases

AllowedKeys is for allowed keys.
Middleware is the Handle implementation.