Teeny.go (or teenygo or only teeny) is a micro-module for create a micro-webserver with support for routes and routes with patterns similar to PHP and JavaScript web-frameworks
For install use
go get -u github.com/inphinit/teeny.go
Then create a file with any name and extension .go, example foo.go and put this content:
package main
import (
"fmt"
"net/http"
"github.com/inphinit/teenygo"
)
func main() {
app := teeny.Serve("localhost", 7000)
app.Action("GET", "/", func (response http.ResponseWriter, request *http.Request) {
fmt.Fprint(response, "Homepage")
})
app.Action("GET", "/about", func (response http.ResponseWriter, request *http.Request) {
fmt.Fprint(response, "About page")
})
app.Exec()
}
For execute local serve run this command:
go run foo.go
For build executes:
go build foo.go
foo
This is a very simple example, for access http://localhost:7000/
and http://localhost:7000/about
Handling Http errors (like ErrorDocument
)
For handling errors for not defined routes (404 Not Found) and when try access a route with invalid (not defined) method uses app.HandlerCodes(codes []int, func TeenyStatusCallback)
, example:
func main() {
app := teeny.Serve("localhost", 7000)
var codes = []int {404, 405}
app.HandlerCodes(codes, func (response http.ResponseWriter, request *http.Request, code int) {
fmt.Fprintf(response, "Error %d", code)
})
...
}
Route patterns
For use patterns in router uses app.Params(method string, path string, func TeenyPatternCallback)
, example with num
and alnum
pattern:
app.Params("GET", "/users/<id:num>/<name:alnum>", func (response http.ResponseWriter, request *http.Request, params map[string]string) {
fmt.Fprint(response, "Params:\n")
for key, value := range params {
fmt.Fprintf(response, "%s = %s\n", key, value)
}
})
Supported patterns:
Pattern | Regex used | Description |
---|---|---|
alnum |
[\da-zA-Z]+ |
Matches routes with param using alpha-numeric in route |
alpha |
[a-zA-Z]+ |
Matches routes with param using A to Z letters in route |
decimal |
\d+\.\d+ |
Matches routes with param using decimal format (like 1.2 , 3.5 , 100.50 ) in route |
num |
\d+ |
Matches routes with param using numeric format in route |
noslash |
[^\/]+ |
Matches routes with param using any character except slashs (\/ or / ) in route |
nospace |
\S+ |
Matches routes with param using any character except spaces, tabs or NUL in route |
uuid |
[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12} |
Matches routes with param using uuid format in route |
version |
\d+\.\d+(\.\d+(-[\da-zA-Z]+(\.[\da-zA-Z]+)*(\+[\da-zA-Z]+(\.[\da-zA-Z]+)*)?)?)? |
Matches routes with param using semver.org format in route |
Top comments (0)