controller

package module
v0.0.0-...-16335fa Latest Latest
Warning

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

Go to latest
Published: Jun 2, 2014 License: MPL-2.0 Imports: 1 Imported by: 1

README

controller

Just the C in MVC (Supports HMVC).

Ok, so I started this repository to explain how I'm doing HMVC with the standard libary without reflection, without taking control of your middleware etc.

Getting Started

From your GOPATH:

go get github.com/d2g/controller

Add a file server.go - for instance, src/myapp/server.go

package main

import (
	"fmt"
	"github.com/d2g/controller"
	"net/http"
	"strings"
)

type ExampleController struct {
	HelloCount int
	base       string
}

func (t *ExampleController) SetBase(base string) controller.HTTPController {
	t.base = base
	return t
}

func (t *ExampleController) Base() string {
	return t.base
}

func (t *ExampleController) Routes() (http.Handler, error) {
	router := http.NewServeMux()
	router.HandleFunc(t.Base(), t.SayHello)
	return router, nil
}

func (t *ExampleController) SayHello(rw http.ResponseWriter, req *http.Request) {
	fmt.Fprint(rw, strings.Repeat("Hello ", t.HelloCount), "World!")
}

type ExampleMiddleware struct {
	controller.HTTPController
	HelloCount *int
}

func (t *ExampleMiddleware) Routes() (http.Handler, error) {
	return t, nil
}

func (t *ExampleMiddleware) ServeHTTP(response http.ResponseWriter, request *http.Request) {
	handler, err := t.HTTPController.Routes()
	if err != nil {
		http.Error(response, err.Error(), 500)
		return
	}

	*t.HelloCount = 3
	handler.ServeHTTP(response, request)
}

func main() {

	example := &ExampleController{
		HelloCount: 1,
	}

	exampleControllers := controller.HTTPControllers([]controller.HTTPController{
		&ExampleMiddleware{
			HTTPController: example.SetBase("/"),
			HelloCount:     &example.HelloCount,
		},
	})

	http.ListenAndServe("localhost:3000", exampleControllers.Routes())
}

Run the server. It will be available on localhost:3000:

go run src/myapp/server.go

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type HTTPController

type HTTPController interface {
	/*
	 * Return the Routes that are managed by this Controller.
	 */
	Routes() (http.Handler, error)

	/*
	 * Sets the Base URL (i.e. /devices/ or /users/ or / ...)
	 */
	SetBase(url string) HTTPController
	/*
	 * Return The Base URL (Needed for Setting Up routing)
	 */
	Base() string
}

* Controllers need to respond with the routes they handle. * This means all routing information is self contained.

type HTTPControllers

type HTTPControllers []HTTPController

func (*HTTPControllers) Routes

func (t *HTTPControllers) Routes() http.Handler

* Return the standard http.Handler for use with the standard net/http

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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