Traffic - Sinatra inspired regexp/pattern mux and web framework for Go

Traffic

Build Status

Package traffic - a Sinatra inspired regexp/pattern mux for Go.

Installation

go get github.com/pilu/traffic

Features

Development Features

development is the default environment. The above middlewares are loaded only in development.

If you want to run your application in production, export TRAFFIC_ENV with production as value.

TRAFFIC_ENV=production your-executable-name

Installation

Dowload the Traffic code:

go get github.com/pilu/traffic

Build the command line tool:

go get github.com/pilu/traffic/traffic

Create a new project:

traffic new hello

Run your project:

cd hello
go build && ./hello

You can use Fresh if you want to build and restart your application every time you create/modify/delete a file.

Example:

The following code is a simple example, the documentation in still in development. For more examples check the examples folder.

package main

import (
  "net/http"
  "github.com/pilu/traffic"
  "fmt"
)

func rootHandler(w traffic.ResponseWriter, r *traffic.Request) {
  fmt.Fprint(w, "Hello World\n")
}

func pageHandler(w traffic.ResponseWriter, r *traffic.Request) {
  params := r.URL.Query()
  fmt.Fprintf(w, "Category ID: %s\n", params.Get("category_id"))
  fmt.Fprintf(w, "Page ID: %s\n", params.Get("id"))
}

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

  // Routes
  router.Get("/", rootHandler)
  router.Get("/categories/:category_id/pages/:id", pageHandler)

  router.Run()
}

Before Filters

You can also add "before filters" to all your routes or just to some of them:

router := traffic.New()

// Executed before all handlers
router.AddBeforeFilter(checkApiKey).
       AddBeforeFilter(addAppNameHeader).
       AddBeforeFilter(addTimeHeader)

// Routes
router.Get("/", rootHandler)
router.Get("/categories/:category_id/pages/:id", pageHandler)

// "/private" has one more before filter that checks for a second api key (private_api_key)
router.Get("/private", privatePageHandler).
        AddBeforeFilter(checkPrivatePageApiKey)

Complete example:

func rootHandler(w traffic.ResponseWriter, r *traffic.Request) {
  fmt.Fprint(w, "Hello World\n")
}

func privatePageHandler(w traffic.ResponseWriter, r *traffic.Request) {
  fmt.Fprint(w, "Hello Private Page\n")
}

func pageHandler(w traffic.ResponseWriter, r *traffic.Request) {
  params := r.URL.Query()
  fmt.Fprintf(w, "Category ID: %s\n", params.Get("category_id"))
  fmt.Fprintf(w, "Page ID: %s\n", params.Get("id"))
}

func checkApiKey(w traffic.ResponseWriter, r *traffic.Request) {
  params := r.URL.Query()
  if params.Get("api_key") != "foo" {
    w.WriteHeader(http.StatusUnauthorized)
  }
}

func checkPrivatePageApiKey(w traffic.ResponseWriter, r *traffic.Request) {
  params := r.URL.Query()
  if params.Get("private_api_key") != "bar" {
    w.WriteHeader(http.StatusUnauthorized)
  }
}

func addAppNameHeader(w traffic.ResponseWriter, r *traffic.Request) {
  w.Header().Add("X-APP-NAME", "My App")
}

func addTimeHeader(w traffic.ResponseWriter, r *traffic.Request) {
  t := fmt.Sprintf("%s", time.Now())
  w.Header().Add("X-APP-TIME", t)
}

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

  // Routes
  router.Get("/", rootHandler)
  router.Get("/categories/:category_id/pages/:id", pageHandler)
  // "/private" has one more before filter that checks for a second api key (private_api_key)
  router.Get("/private", privatePageHandler).
          AddBeforeFilter(checkPrivatePageApiKey)

  // Executed before all handlers
  router.AddBeforeFilter(checkApiKey).
         AddBeforeFilter(addAppNameHeader).
         AddBeforeFilter(addTimeHeader)

  router.Run()
}

Author

More

Comments
  • Can't set Header on NotFoundHandler

    Can't set Header on NotFoundHandler

    I'm trying to override the content-type for the NotFoundHandler to be in Content-Type: application/json; charset=utf-8 but it seems like its still using Content-Type: text/plain even with beforeFilter setup.

  • Need an AfterFilter

    Need an AfterFilter

    I need a filter that executes both before and after a route has executed. I'm trying to add miniprofiler support to traffic, and so need to run a finalizer to stop some timers.

  • Multipe calls to WriteHeader ?

    Multipe calls to WriteHeader ?

    I have a handler which calls WriteHeader(int) on a traffic.ResponseWriter. However I get in the log:

    2014/08/21 13:15:11 http: multiple response.WriteHeader calls
    

    I've confirmed the handler itself only calls it once, and looking at the implementation in traffic I don't see why the error is happening. Nothing seems to break but the "error" is logged.

  • Replace ServeFile with ServeContent to use previously opened file

    Replace ServeFile with ServeContent to use previously opened file

    The previous security fix was just about right but didn't work for one small corner case, that is if you have a file in the public directory with the same name as a file anywhere else on the system, someone can request the file in another location and retrieve it.

    To fix this I replace ServeFile with ServeContent, this also will not open the file twice to serve it.

  • no need

    no need "w" argument

    Show this message cannot use w (type traffic.ResponseWriter) as type string in function argument when I run the appengine example. I fix it. PR , pls.

  • Error when trying

    Error when trying "go get"

    Hi, first of all I want to thank you for your great work.

    I'm using your package in a development workstation based on Mac OSX, everything works great but when trying to install the package on my development server (Ubuntu 12.04 32bits) I get the following output:

    go get github.com/pilu/traffic
    
    /usr/lib/go/src/pkg/github.com/pilu/config/config.go:20: commentSplitRegexp.Split undefined (type *regexp.Regexp has no field or method Split)
    /usr/lib/go/src/pkg/github.com/pilu/config/config.go:51: keyValueSplitRegexp.Split undefined (type *regexp.Regexp has no field or method Split)
    
  • added RunSSL

    added RunSSL

    To service an HTTPS connection instead of HTTP just run RunSSL with certfile and keyfile instead of ordinary Run. Thanks @pilu for the suggestion. Was a very easy fix.

Simple and lightweight Go web framework inspired by koa
Simple and lightweight Go web framework inspired by koa

VOX A golang web framework for humans, inspired by Koa heavily. Getting started Installation Using the go get power: $ go get -u github.com/aisk/vox B

Dec 14, 2022
⚡️ Express inspired web framework written in Go
⚡️ Express inspired web framework written in Go

Fiber is an Express inspired web framework built on top of Fasthttp, the fastest HTTP engine for Go. Designed to ease things up for fast development w

Jan 2, 2023
A Go framework for building JSON web services inspired by Dropwizard

Tiger Tonic A Go framework for building JSON web services inspired by Dropwizard. If HTML is your game, this will hurt a little. Like the Go language

Dec 9, 2022
Rocinante is a gin inspired web framework built on top of net/http.

Rocinante Rocinante is a gin inspired web framework built on top of net/http. ⚙️ Installation $ go get -u github.com/fskanokano/rocinante-go ⚡️ Quicks

Jul 27, 2021
Gouweb: A web framework for go inspired by laravel

gouweb is a web framework for go inspired by laravel Installation go get -u gith

Feb 17, 2022
Go-igni: monolith-based web-framework in Go Inspired by classical PHP Frameworks like CodeIgnier & Laravel

go-igni Web Framework in Go About This is research project about developing monolith-based web-framework in Go Inspired by classical PHP Frameworks li

Feb 25, 2022
Golanger Web Framework is a lightweight framework for writing web applications in Go.

/* Copyright 2013 Golanger.com. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except

Nov 14, 2022
The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework.

jin About The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework. If thi

Jul 14, 2022
Simple go endpoint with gorilla / mux routing, testing, dockerfile

Simple go endpoint with gorilla / mux routing, testing, dockerfile

Feb 1, 2022
⚡ Rux is an simple and fast web framework. support middleware, compatible http.Handler interface. 简单且快速的 Go web 框架,支持中间件,兼容 http.Handler 接口

Rux Simple and fast web framework for build golang HTTP applications. NOTICE: v1.3.x is not fully compatible with v1.2.x version Fast route match, sup

Dec 8, 2022
Roche is a Code Generator and Web Framework, makes web development super concise with Go, CleanArch
Roche is a Code Generator and Web Framework, makes web development super concise with Go, CleanArch

It is still under development, so please do not use it. We plan to release v.1.0.0 in the summer. roche is a web framework optimized for microservice

Sep 19, 2022
A powerful go web framework for highly scalable and resource efficient web application

webfr A powerful go web framework for highly scalable and resource efficient web application Installation: go get -u github.com/krishpranav/webfr Exa

Nov 28, 2021
A powerful go web framework for highly scalable and resource efficient web application

A powerful go web framework for highly scalable and resource efficient web application

Oct 3, 2022
A web app built using Go Buffalo web framework

Welcome to Buffalo Thank you for choosing Buffalo for your web development needs. Database Setup It looks like you chose to set up your application us

Feb 7, 2022
Dec 28, 2022
hiboot is a high performance web and cli application framework with dependency injection support

Hiboot - web/cli application framework About Hiboot is a cloud native web and cli application framework written in Go. Hiboot is not trying to reinven

Nov 20, 2022
Package macaron is a high productive and modular web framework in Go.
Package macaron is a high productive and modular web framework in Go.

Macaron Package macaron is a high productive and modular web framework in Go. Getting Started The minimum requirement of Go is 1.6. To install Macaron

Jan 2, 2023
A minimal framework to build web apps; with handler chaining, middleware support; and most of all standard library compliant HTTP handlers(i.e. http.HandlerFunc).
A minimal framework to build web apps; with handler chaining, middleware support; and most of all standard library compliant HTTP handlers(i.e. http.HandlerFunc).

WebGo v4.1.3 WebGo is a minimalistic framework for Go to build web applications (server side) with zero 3rd party dependencies. Unlike full-fledged fr

Jan 1, 2023