/gorouter

A simple HTTP router for Go

Primary LanguageGoApache License 2.0Apache-2.0

gorouter

A simple HTTP router for Go.

Reimplemented Custom HTTP Routing in Go to write human-readable routes and to easily parse values from URI.

Install

$ go get -u github.com/alseiitov/gorouter

Example

package main

import (
	"log"
	"net/http"

	"github.com/alseiitov/gorouter"
)

type response struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

func userHandler(ctx *gorouter.Context) {
	name, err := ctx.GetStringParam("name")
	if err != nil {
		ctx.WriteError(http.StatusBadRequest, err.Error())
		return
	}

	age, err := ctx.GetIntParam("age")
	if err != nil {
		ctx.WriteError(http.StatusBadRequest, err.Error())
		return
	}

	ctx.WriteJSON(http.StatusOK, response{Name: name, Age: age})
}

func main() {
	router := gorouter.NewRouter()
	router.GET(`/user/:name/:age`, userHandler)

	log.Fatalln(http.ListenAndServe(":9000", router))
}
$ curl -i "http://localhost:9000/user/John/23" 
HTTP/1.1 200 OK
Content-Type: application/json
Date: Wed, 03 Mar 2021 09:56:53 GMT
Content-Length: 24

{"name":"John","age":23}