Simple HTTP router for Go

Related tags

Routers go http
Overview

ngamux

Simple HTTP router for Go



Installation

Run this command with correctly configured Go toolchain.

go get github.com/ngamux/ngamux

Examples

package main

import(
  "net/http"
  "github.com/ngamux/ngamux"
)

func main() {
  mux := ngamux.NewNgamux()
  mux.Get("/", func(rw http.ResponseWriter, r *http.Request) {
    ngamux.JSON(rw, map[string]string{
      "message": "welcome!",
    })
  })
  
  http.ListenAndServe(":8080", mux)
}

Todo

  • Multiple handler (middleware for each route)
  • Route group
  • Route params (in URL parameters)
Issues
  • [PROPOSAL] Refactor Group Code

    [PROPOSAL] Refactor Group Code

    Usage Example

    package main
    
    import (
      "fmt"
      "log"
      "net/http"
      "time"
    
      "github.com/ngamux/ngamux"
    )
    
    func handler(rw http.ResponseWriter, r *http.Request) error {
      fmt.Fprintln(rw, r.URL.Path)
      return nil
    }
    
    func mw(next ngamux.HandlerFunc) ngamux.HandlerFunc {
      return func(rw http.ResponseWriter, r *http.Request) error {
        now := time.Now()
        defer func() {
          log.Println(r.URL.Path, time.Since(now))
        }()
    
        return next(rw, r)
      }
    }
    
    func main() {
      mux := ngamux.NewNgamux()
    
      mux.GroupPrefix("/api", func(api *ngamux.Ngamux) {
        api.Get("/foo", mw(handler))
        api.Get("/bar", mw(handler))
      })
    
      http.ListenAndServe(":8080", mux)
    }
    
    
    opened by clavinjune 11
  • is it ready to be version 1, now?

    is it ready to be version 1, now?

    I need to communicate with all public users, testers, and contributors about version tagging of this HTTP router. is it ready to be version 1, now?

    let me mention all contributors: @born2ngopi @ClavinJune @milhamsuryapratama

    opened by hadihammurabi 9
  • [PROPOSAL] Wrap http.ResponseWriter and *http.Request in Context

    [PROPOSAL] Wrap http.ResponseWriter and *http.Request in Context

    Some reasons we need to wrap http.ResponseWriter and *http.Request is:

    • cleaner route handler
    • manage request and response in one place
    • like most http router (Fiber, Echo)

    Then we need create one place that contains http.ResponseWriter and *http.Request inside that can manage both easily. It could be like this.

    func IndexHandler(c *ngamux.Ctx) error {
    }
    

    If we see deeper, the Ctx type will be like this.

    type Ctx struct {
      rw http.ResponseWriter
      r *http.Request
    }
    
    // request
    func (c Ctx) GetParam(key string) string
    func (c Ctx) GetJSON(store interface{}) error
    
    // response
    func (c Ctx) String(key string) error
    func (c Ctx) JSON(data interface{}) error
    
    // other method implementation here
    
    opened by hadihammurabi 6
  • Little revamp for ngamux to moving into interface base style code

    Little revamp for ngamux to moving into interface base style code

    Hi I've made some changes, to moving ngamux to use interface for clearance purpose rather than directly returns struct of definition of ngamux, for detail please check the commit messages.

    opened by muhammadisa 1
  • [BUG] Handle Error Produced by Handler

    [BUG] Handle Error Produced by Handler

    Describe the bug Handler has error as return value. It can be nil if no errors. Otherwise, error object if an error happen.

    To Reproduce Steps to reproduce the behavior:

    1. Create route and bind with handler
    mux.Get("/", func(rw http.ResponseWriter, r *http.Request) error {
      return errors.New("something bad")
    })
    
    1. The error is not handled.

    Expected behavior Should send HTTP response with error message and status.

    bug hacktoberfest 
    opened by hadihammurabi 1
  • [FEATURE] implementing global middleware

    [FEATURE] implementing global middleware

    for implement global middleware, we can use method for assign middleware to route/handler

    example:

    mux.Use(func(next ngamux.HandlerFunc) ngamux.HandlerFunc {
    	return func(rw http.ResponseWriter, r *http.Request) error {
    		fmt.Println("hello from middleware")
    		return next(rw, r)
    	}
    })
    
    opened by milhamsuryapratama 1
  • [BUG] fixing panic when route not found

    [BUG] fixing panic when route not found

    Describe The Bug

    foundRoute handler is replaced with nil whenever a route is not found

    To Reproduce

    1. Run example/basic/basic.go
    2. Access unregistered endpoint (e.g: https://localhost:8080/foobar)
    3. Golang panics

    Expected Behavior

    r.config.NotFoundHandler is called

    Additional Context

    https://github.com/ngamux/ngamux/blob/5f35c09b6819d402a387089d3d578b282499e2a1/ngamux.go#L138-L142 the foundroute is always replaced

    opened by clavinjune 1
  • [FEATURE] add panic handler to avoid panic on serving HTTP requests

    [FEATURE] add panic handler to avoid panic on serving HTTP requests

    Description

    In Order to avoid panicking when serving HTTP Requests, I implement the basic panicHandler, read the example/panic/main.go for full usage example

    opened by clavinjune 0
  • add middleware and change logic copy routesMap

    add middleware and change logic copy routesMap

    add recovery and cors in middleware with example how to use

    change logic copy routesMap, why we must change previous logic. because the previous logic only copy first map. and not copy second map. for performance

    before:

    Concurrency Level:      1
    Time taken for tests:   56.737 seconds
    Complete requests:      100000
    Failed requests:        0
    Total transferred:      13500000 bytes
    HTML transferred:       2700000 bytes
    Requests per second:    1762.52 [#/sec] (mean)
    Time per request:       0.567 [ms] (mean)
    Time per request:       0.567 [ms] (mean, across all concurrent requests)
    Transfer rate:          232.36 [Kbytes/sec] received
    

    after:

    Concurrency Level:      1
    Time taken for tests:   32.535 seconds
    Complete requests:      100000
    Failed requests:        0
    Total transferred:      13600000 bytes
    HTML transferred:       2800000 bytes
    Requests per second:    3073.65 [#/sec] (mean)
    Time per request:       0.325 [ms] (mean)
    Time per request:       0.325 [ms] (mean, across all concurrent requests)
    Transfer rate:          408.22 [Kbytes/sec] received
    
    
    opened by born2ngopi 0
  • improve more performa in matching route

    improve more performa in matching route

    I've done performance testing using apache banchmark with the following results

    cpu : Intel(R) Core(TM) i7-6600U CPU @ 2.60GHz

    before :

    Document Path:          /users/123/slug-name
    Document Length:        0 bytes
    
    Concurrency Level:      1
    Time taken for tests:   18.295 seconds
    Complete requests:      100000
    Failed requests:        0
    Total transferred:      7500000 bytes
    HTML transferred:       0 bytes
    Requests per second:    5466.11 [#/sec] (mean)
    Time per request:       0.183 [ms] (mean)
    Time per request:       0.183 [ms] (mean, across all concurrent requests)
    Transfer rate:          400.35 [Kbytes/sec] received
    
    

    after:

    Document Path:          /users/123/slug-name
    Document Length:        0 bytes
    
    Concurrency Level:      1
    Time taken for tests:   16.679 seconds
    Complete requests:      100000
    Failed requests:        0
    Total transferred:      7500000 bytes
    HTML transferred:       0 bytes
    Requests per second:    5995.52 [#/sec] (mean)
    Time per request:       0.167 [ms] (mean)
    Time per request:       0.167 [ms] (mean, across all concurrent requests)
    Transfer rate:          439.13 [Kbytes/sec] received
    
    

    kan lumayan XD

    opened by born2ngopi 0
  • [PROPOSAL] Return Header Only on Head Request

    [PROPOSAL] Return Header Only on Head Request

    Is your feature request related to a problem? Please describe. Some conditions, we need to get response header only. It can do by send request using HEAD method. But, I can't do it using this library.

    Describe the solution you'd like Check HEAD request method for all request. Remove the body and send header only.

    References:

    • https://reqbin.com/Article/HttpHead
    opened by hadihammurabi 6
Releases(v1.0.4)
  • v1.0.4(Mar 14, 2022)

    v1.0.4 (2022-03-14)

    Fix

    • mux: register route all to all supported methods
    • ngamux: change NewNgamux to New
    • route: no matched because method replaced

    Refactor

    • common: test using golang-must assertion lib
    • config: test using golang-must assertion lib
    • group: test using golang-must assertion lib
    • handler: test using golang-must assertion lib
    • mux: test using golang-must assertion lib
    • ngamux: fix golint
    • ngamux: fix golint
    • ngamux: fix golint
    • route: test using golang-must assertion lib

    Chore

    • ci test show coverage
    • ci lint and test
    • improve golint
    • git-chglog init
    • common: fix misspell in comments

    Feat

    • ngamux: benchmark add and get route
    Source code(tar.gz)
    Source code(zip)
  • v1.0.3(Sep 26, 2021)

    In this release, ngamux has increased on code coverage by more than 70%. ngamux

    Change Log

    v1.0.3 (2021-09-26)

    Feat

    • common: test TestGetQuery
    • common: test TestGetParam
    • common: test TestSetContextValue
    • common: test TestGetContextValue
    • common: test TestString
    • common: test TestStringWithStatus
    • common: test TestJSON
    • common: test TestJSONWithStatus
    • common: test WithMiddlewares
    • common: test TestGetJSON
    • config: test TestBuildConfig
    • group: test TestGroup
    • handler: test TestServeHTTP
    • mux: test TestGet
    • mux: test TestNewNgamux
    • mux: test TestPut
    • mux: test TestPatch
    • mux: test TestDelete
    • mux: test TestAll
    • mux: test TestPost
    • mux: test TestUse
    • route: test TestBuildRoute
    • route: test TestAddRoute
    • route: test TestGetRoute

    Fix

    • mux: route param finder with number and chars
    • mux: route method all matching
    • mux: send error object to global error handler
    Source code(tar.gz)
    Source code(zip)
  • v1.0.2(Sep 21, 2021)

    This is patch release, the last release was enhanced without API breaking changes. Here what is included in this release:

    • change NotFoundHandler to GlobalErrorHandler with error data in req context value
    • apply global middleware for GlobalErrorHandler
    • add Map type to simplify JSON response
    • add func to send string response
    Source code(tar.gz)
    Source code(zip)
  • v1.0.1(Sep 20, 2021)

    This is patch release that improve the last release without API breaking changes. Here what is included in this release:

    • fix route parameters matching with some characters (dot, minus, underscore)
    • add feature to create handler with all request method (mux.All)
    • refactor internal code for readability
    Source code(tar.gz)
    Source code(zip)
  • v1.0.0(Sep 19, 2021)

    After some days of development, core API, implementation, and ecosystem are ready to use. Here what features are included in this release.

    • HTTP handler
    • HTTP router
    • Route group
    • Router middleware (global, group, specific route)
    • Route (URL) parameters
    • Utilities to build router, get data from request and write data for response
    • Provided basic middlewares

    This is major release that means all changes included here are stable. Any future changes will released as patch or minor under this major until we doing big change that need to move to next major release.

    Source code(tar.gz)
    Source code(zip)
xujiajun/gorouter is a simple and fast HTTP router for Go. It is easy to build RESTful APIs and your web framework.

gorouter xujiajun/gorouter is a simple and fast HTTP router for Go. It is easy to build RESTful APIs and your web framework. Motivation I wanted a sim

徐佳军 525 May 29, 2022
Fast, simple, and lightweight HTTP router for Golang

Sariaf Fast, simple and lightweight HTTP router for golang Install go get -u github.com/majidsajadi/sariaf Features Lightweight compatible with net/ht

defectivepixel 33 Mar 3, 2022
Simple router build on `net/http` supports custom middleWare.

XMUS-ROUTER Fast lightweight router build on net/http supports delegate and in url params. usage : Create new router using NewRouter() which need rout

amupxm [amir hossein mokarrami far] 5 Dec 27, 2021
Simple HTTP router for Go

ngamux Simple HTTP router for Go Installation Examples Todo Installation Run this command with correctly configured Go toolchain. go get github.com/ng

null 51 Jun 1, 2022
Simple http router.

Simple router based on tree structure. import ( "fmt" "log" "net/http" router "github.com/dmitruk-v/router/v1" ) func main() { ro := router.New

Valeriy Dmitruk 0 Dec 29, 2021
FastRouter is a fast, flexible HTTP router written in Go.

FastRouter FastRouter is a fast, flexible HTTP router written in Go. FastRouter contains some customizable options, such as TrailingSlashesPolicy, Pan

Razon Yang 21 Apr 19, 2022
Go Server/API micro framework, HTTP request router, multiplexer, mux

?? gorouter Go Server/API micro framework, HTTP request router, multiplexer, mux. ?? ABOUT Contributors: Rafał Lorenz Want to contribute ? Feel free t

Rafał Lorenz 128 Jun 13, 2022
A high performance HTTP request router that scales well

HttpRouter HttpRouter is a lightweight high performance HTTP request router (also called multiplexer or just mux for short) for Go. In contrast to the

Julien Schmidt 14.2k Jun 26, 2022
High-speed, flexible tree-based HTTP router for Go.

httptreemux High-speed, flexible, tree-based HTTP router for Go. This is inspired by Julien Schmidt's httprouter, in that it uses a patricia tree, but

Daniel Imfeld 545 Jun 23, 2022
:rotating_light: Is a lightweight, fast and extensible zero allocation HTTP router for Go used to create customizable frameworks.

LARS LARS is a fast radix-tree based, zero allocation, HTTP router for Go. view examples. If looking for a more pure Go solution, be sure to check out

Go Playgound 387 Jun 11, 2022
A powerful HTTP router and URL matcher for building Go web servers with 🦍

gorilla/mux https://www.gorillatoolkit.org/pkg/mux Package gorilla/mux implements a request router and dispatcher for matching incoming requests to th

Gorilla Web Toolkit 16.8k Jun 22, 2022
An extremely fast Go (golang) HTTP router that supports regular expression route matching. Comes with full support for building RESTful APIs.

ozzo-routing You may consider using go-rest-api to jumpstart your new RESTful applications with ozzo-routing. Description ozzo-routing is a Go package

Ozzo Framework 438 Jun 15, 2022
Pure is a fast radix-tree based HTTP router

package pure Pure is a fast radix-tree based HTTP router that sticks to the native implementations of Go's "net/http" package; in essence, keeping the

Go Playgound 126 Jun 25, 2022
Go HTTP router

violetear Go HTTP router http://violetear.org Design Goals Keep it simple and small, avoiding extra complexity at all cost. KISS Support for static an

Nicolas Embriz 105 Mar 21, 2022
lightweight, idiomatic and composable router for building Go HTTP services

chi is a lightweight, idiomatic and composable router for building Go HTTP services. It's especially good at helping you write large REST API services

go-chi 11.7k Jun 26, 2022
:tongue: CleverGo is a lightweight, feature rich and high performance HTTP router for Go.

CleverGo CleverGo is a lightweight, feature rich and trie based high performance HTTP request router. go get -u clevergo.tech/clevergo English 简体中文 Fe

CleverGo Web Framework 251 May 30, 2022
Fast and flexible HTTP router

treemux - fast and flexible HTTP router Basic example Debug logging CORS example Error handling Rate limiting using Redis Gzip compression OpenTelemet

Vladimir Mihailenco 441 Jun 25, 2022
Lightweight Router for Golang using net/http standard library with custom route parsing, handler and context.

Go-Lightweight-Router Lightweight Router for Golang using net/http standard library with custom route parsing, handler and context. Further developmen

null 0 Nov 3, 2021
A high performance HTTP request router that scales well

HttpRouter HttpRouter is a lightweight high performance HTTP request router (also called multiplexer or just mux for short) for Go. In contrast to the

Julien Schmidt 13.5k Dec 9, 2021