rou

package module
v1.1.3 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2022 License: MIT Imports: 5 Imported by: 0

README

Simple HTTP router

A simple HTTP router built on top of the Golang http library

Install

rou is a standard Go module which can be installed with:

go get github.com/Moranilt/rou

Usage

package main

import (
  "github.com/Moranilt/rou"
)

const (
  authError = "Authorization header should be provided"
  requestDataError = "X-Request-Data header should be provided"
)

func GET_UserHandler(ctx *rou.Context) {
  userId := ctx.RouterParams().Get("userId") // Extract params from router
  // etc
  io.WriteString(ctx.ResponseWriter(), "Response message")
}

func GET_UsersPostHandler(ctx *rou.Context) {
  userId := ctx.RouterParams().Get("userId") // Extract params from router
  postId := ctx.RouterParams().Get("postId") // Extract params from router
  // etc
  io.WriteString(ctx.ResponseWriter(), "Response message")
}

func POST_UserHandler(ctx *rou.Context) {
  // your actions
}

func AuthMiddleware(w http.ResponseWriter, r *http.Request) bool {
	if r.Header.Get("Authorization") == "" {
		io.WriteString(w, authError)
		return false
	}
	return true
}

func RequestDataMiddleware(w http.ResponseWriter, r *http.Request) bool {
	if r.Header.Get("X-Request-Data") == "" {
		io.WriteString(w, requestDataError)
		return false
	}
	return true
}

func main() {
  router := rou.NewRouter()
  router.Middleware(AuthMiddleware)
  router.Get("/users/:userId", GET_UserHandler).Middleware(RequestDataMiddleware)
  router.Get("/users/:userId/posts/:postId", GET_UsersPostHandler)
  router.Post("/users/create", POST_UserHandler)
  router.Put(...)
  router.Patch(...)
  router.Delete(...)
  router.Head(...)
  router.Options(...)

  log.Fatal(router.RunServer(":8080")) // Runs server on http://localhost:8080
}

Documentation

Index

Constants

View Source
const (
	MethodGet     = "GET"
	MethodPost    = "POST"
	MethodPut     = "PUT"
	MethodPatch   = "PATCH"
	MethodDelete  = "DELETE"
	MethodOptions = "OPTIONS"
	MethodHead    = "HEAD"
)
View Source
const (
	MessageBodyIsNotValid   = "Request body is not valid"
	MessageMethodNotAllowed = "Method not allowed"
	MessagePageNotFound     = "Page not found"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Context

type Context struct {
	// contains filtered or unexported fields
}

func (Context) ErrorJSONResponse added in v1.1.1

func (c Context) ErrorJSONResponse(status int, message string)

func (Context) Params

func (c Context) Params() url.Values

Returns query params of request

func (Context) Request

func (c Context) Request() *http.Request

Returns basic HTTP request object

func (Context) ResponseWriter

func (c Context) ResponseWriter() http.ResponseWriter

Returns basic HTTP response writer

func (Context) RouterParams

func (c Context) RouterParams() Storage

Returns RouterParams structure with params of route as key value

If you have route "/user/:id/posts/:postId" and request URL path "/user/1/posts/45" RouterParams will have map with keys took from route and values which it will take from request URL path `["id": "1", "postId": "45"]`

func (*Context) SetContentType added in v1.1.1

func (ctx *Context) SetContentType(contentType string)

Set response content type

func (Context) SuccessJSONResponse added in v1.1.1

func (c Context) SuccessJSONResponse(body any)

type ErrorObject

type ErrorObject struct {
	Message string `json:"message"`
	Code    int    `json:"code"`
}

type MiddlewareFunction added in v1.1.3

type MiddlewareFunction func(http.ResponseWriter, *http.Request) bool

type ResponseObject

type ResponseObject[T any] struct {
	Error *ErrorObject `json:"error"`
	Body  T            `json:"body"`
}

type Route

type Route struct {
	Path    string
	Handler func(*Context)
	// contains filtered or unexported fields
}

func (*Route) Middleware added in v1.1.3

func (r *Route) Middleware(middlewares ...MiddlewareFunction)

Store all middllewares for a specific router

Every middleware should return TRUE if the rule succeeds If the middleware returns FALSE - other middlewares will not be triggered

type RouterMethods added in v1.1.3

type RouterMethods interface {
	Middleware(middlewares ...MiddlewareFunction)
}

type SimpleRouter

type SimpleRouter struct {
	Routes      *routes
	ContentType string
	// contains filtered or unexported fields
}

Initial struct to create HTTP server provide this structure to http.ListenAndServe function It has a list of routes which is stored to serve

func NewRouter

func NewRouter() *SimpleRouter

Create a new SimpleRouter instance

func (SimpleRouter) Delete

func (sr SimpleRouter) Delete(route string, handler func(*Context)) RouterMethods

Add route by method DELETE

func (SimpleRouter) Get

func (sr SimpleRouter) Get(route string, handler func(*Context)) RouterMethods

Add route by method GET

func (SimpleRouter) GetRoutes

func (sr SimpleRouter) GetRoutes(method string) []*Route

func (SimpleRouter) Head

func (sr SimpleRouter) Head(route string, handler func(*Context)) RouterMethods

Add route by method HEAD

func (SimpleRouter) Options

func (sr SimpleRouter) Options(route string, handler func(*Context))

Add route by method OPTIONS

func (SimpleRouter) Patch

func (sr SimpleRouter) Patch(route string, handler func(*Context)) RouterMethods

Add route by method PATCH

func (SimpleRouter) Post

func (sr SimpleRouter) Post(route string, handler func(*Context)) RouterMethods

Add route by method POST

func (SimpleRouter) Put

func (sr SimpleRouter) Put(route string, handler func(*Context)) RouterMethods

Add route by method PUT

func (*SimpleRouter) RunServer added in v1.1.1

func (sr *SimpleRouter) RunServer(addr string) error

Runs server with http.ListenAndServe

func (*SimpleRouter) ServeHTTP

func (sr *SimpleRouter) ServeHTTP(w http.ResponseWriter, r *http.Request)

Implements an http.Handler interface to use it like server handler in http.ListenAndServe

func (*SimpleRouter) Use added in v1.1.3

func (sr *SimpleRouter) Use(middlewares ...MiddlewareFunction)

type Storage

type Storage interface {
	Delete(name string)
	Has(name string) bool
	Set(name, value string)
	Get(name string) string
}

Jump to

Keyboard shortcuts

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