router

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2025 License: MIT Imports: 2 Imported by: 1

README

go-router

Deadly simple router

Usage

package main

import (
	"github.com/zelenin/go-router"
	"log"
	"net/http"
)

func main() {
	rtr := router.New()

	rtr.Pipe(logger)

	rtr.HandleFunc("GET /ping", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("pong"))
	})

	rtr.Group("/api/", func(subRouter *router.Router) {
		subRouter.Group("/posts/", func(subRouter *router.Router) {
			subRouter.Handle(`GET /{id}`, postHandler{})
		})
	})

	server := &http.Server{
		Addr:    ":8080",
		Handler: rtr,
	}

	err := server.ListenAndServe()
	if err != nil {
		log.Fatal(err)
	}
}

type postHandler struct{}

func (handler postHandler) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	id := req.PathValue("id")
	res.Write([]byte("id: " + id))
}

func logger(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Printf("[logger] Connection from %s", r.RemoteAddr)
		next.ServeHTTP(w, r)
	})
}

Notes

  • WIP. Library API can be changed in the future

Author

Aleksandr Zelenin, e-mail: aleksandr@zelenin.me

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Router

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

func New

func New() *Router

func (*Router) Group

func (r *Router) Group(pattern string, fn func(*Router))

func (*Router) Handle

func (r *Router) Handle(pattern string, handler http.Handler)

func (*Router) HandleFunc

func (r *Router) HandleFunc(pattern string, handlerFunc http.HandlerFunc)

func (*Router) Pipe

func (r *Router) Pipe(middleware func(http.Handler) http.Handler)

func (*Router) ServeHTTP

func (r *Router) ServeHTTP(res http.ResponseWriter, req *http.Request)

Jump to

Keyboard shortcuts

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