gotojs

package module
v0.0.0-...-9ccfb5e Latest Latest
Warning

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

Go to latest
Published: May 30, 2016 License: BSD-3-Clause Imports: 26 Imported by: 0

README

gotojs

Package gotojs offers a library for exposing go-interfaces as HTTP based RPC enpoints and pre-generated JavaScript proxy objects. In a first step gotojs exposes go-interfaces,function, attributes and handler implementations as a HTTP based API by transforming the go-internal signature to a HTTP service. Parameters and return objects are encoded using JSON structures. A set of JavaScript proxy objects are assembled which are forwarding JS calls to the server-side go-implementation using JSON encoded Ajax requests. General client applications can directly access the HTTP based API service via given URL-structure whereby HTML5 based web-application using jQuery,YUI and other simalar frameworks just need to load the corresponding JS proxy objects (engine) in order to transparently access the actual go-implementation.

Usage

Build an API

Define the Service as a struct and add the methods.

import . "github.com/sebkl/gotojs"

Type MyService struct {
}

func (s MyService) Echo(in string) string {
 return in
}

Initialize the gotojs engine and the service itself:

co := NewContainer()
se := MyService{}

The container may be initialized with further parameters that affect its way working.

Expose the service methods under a given name (context: myservice)

co.ExposeInterface(se,"myservice")

A wide range of further exposure methods are supported such as exposing entire interfaces, sets of interface methods, single functions or just properties.

Launch the server at web context "/" and listen on port 8080:

co.Start(":8080","/myapp")

The container itself implements the http handler interface ServeHTTP and thus can be easily integrated in existing environments

Client side

For accessing the JavasScript bindings, the engine has to be loaded first:

<script src="/myapp/gotojs"></script>

Once loaded each exposed function can be directly invoked in the JavaScript code, whereby the last argument is always the asynchronous data handler callback:

GOTOJS.myservice.Echo("Hello World!",function(d) { console.log(d); })

Each function or method is actually exposed as /context/interface/method:

#> curl "http://localhost:8080/myapp/myservice/Echo?p=Hello"
"Hello"

#> curl "http://localhost:8080/myapp/myservice/Echo/World"
"World"

A golang based client implementation:

client := NewClient("http://localhost:8080/myapp")
ret,err := client.Invoke("myservice","Echo","Hello World!")
Further features

Expose static documents such as html and css files:

fe.EnableFileServer("local/path/to/htdocs","/files")

In this way it is supposed to make the Document root available which contains the main web-application files.

Error handling:

fe.ExposeFunction(func(hc *HTTPContext) { hc.Errorf(404,"To be Implemented") },"Service","TestError");

More to be listed here

  • More complex data structures and converters
  • Filtering
  • Injections
  • Binary content
  • Remote bindings
  • Data streams
  • Error handling
GO vs JS signatures

The below map shows how exposed go-interfaces are being called using the JS proxy object.

GO implementation JS call Description
func Foo(a,b int) (c int) var c = GOTOJS.Service.Foo(a,b); Synchronous call (deprecated)
func Foo(a,b int) (c int) GOTOJS.Service.Foo(a,b,function(c) { ... }); Asynchronous call: The callback is always the last argument of the method call.
func Foo(postBody *BinaryContent) (b int) GOTOJS.Service.Foo(postBody,mimetype,function(b) { ... }); Call with plain untouched post body data.
func Foo(w http.ResponseWriter, r *http.Request) GOTOJS.Service.Foo(postBody,mimetype,function(w) { ... }); A handler function exposed as such, receives the transmitted data in the request object and replies via the response writer.

Examples

A list of more comprehensive examples can be found below:

  1. Basic function exposure
  2. Basic interface exposure
  3. A simple web application
  4. Dealing with sessions
  5. Inline exposures
  6. Handler exposure for integration of existing HTTP interfaces
  7. Standard handler exposures

More to come...

Google App Engine Example:
package gaeexample

import (
	. "github.com/sebkl/gotojs"
	. "github.com/sebkl/gotojs/gae"
)

func init() {
	container := NewContainer()

	/* Define function that just returns all header of a incoming http request */
	f:= func (c *gae.Context) map[string][]string {
		/* Context is injected by the gae integration package. */
		return c.HTTPContext.Request.Header
	}

	/* Expose/bind function: */
	container.ExposeFunction(f,"EchoService","Header")

	SetupAndStart(container)
}

Which actually implements a simple HTTP Trace service (@ /gotojs/EchoService/Header) for demonstration purposes.

Generate an application base:

For a quick example application including predefined templates and javascript libraries a builtin tool may be used:

go get github.com/sebkl/gotojs/util
${GOPATH}/bin/util example ${GOPATH}/www

Requirements

Gotojs requires

  • go version >= 1.3 since some reflection features are used from package reflect that have been added in 1.3 Please keep in mind, that the example application ${GOPATH}/www/app.go is intended to show some basic features.

Documentation

The go documentation of the gotojs package is complete and includes some additional examples for various use cases. It can be found at godoc.org.

Development

For development purposes more dependencies are required due to nodejs unit testing:

If not happend so far create your go environment and set the GOPATH environment variable accordingly:

#mkdir ~/go
#export GOPATH=~/go

Check your go, nodejs and npm versions:

#go version
go version go1.3 linux/amd64
#node --version
v0.10.20
#npm --version
1.3.11
#npm list jquery@1.8.3
└── jquery@1.8.3
#npm list request
└─┬ jquery@1.8.3
  └─┬ jsdom@0.2.19
    └── request@2.55.0

If these are not available, please try to install at least the above listed version. The nodejs stuff is necessary to perform the go unit tests.

TODO

A list of implementation aspects that is currently being worked on:

  • Integrate with grpc
    • Generate proto while exposing interface
    • support ProtocolBuffers as transport encoding (besides JSON)
  • Support GCP Pub/Sub as stream.

Documentation

Overview

Package gotojs offers a library for exposing go-interfaces as Javascript proxy objects. Therefore gotojs assembles a JS engine which creates proxy objects as JS code and forwards the calls to them via JSON encoded HTTP Ajax requests. This allows web developers to easily write HTML5 based application using jQuery,YUI and other simalar frameworks without explictily dealing with ajax calls and RESTful server APIs but using a transparent RPC service.

This service includes the follwing features:

- Injection of Objects (like a session or http context)

- Automatic include of external and internal libaries while the engine is loaded.

- Routing to internal fileserver that serves static content like images and html files.

Index

Examples

Constants

View Source
const (
	DefaultInterfaceName         string = "main"
	DefaultFunctionName          string = "f"
	DefaultInternalInterfaceName string = "gotojs"
)
View Source
const (
	F_CLEAR            = 0
	F_LOAD_LIBRARIES   = 1 << iota
	F_LOAD_TEMPLATES   = 1 << iota
	F_VALIDATE_ARGS    = 1 << iota
	F_ENABLE_ACCESSLOG = 1 << iota
	F_ENABLE_MINIFY    = 1 << iota
	F_DEFAULT          = F_LOAD_LIBRARIES |
		F_LOAD_TEMPLATES |
		F_ENABLE_ACCESSLOG |
		F_ENABLE_MINIFY

	F_DEVELOPMENT = F_LOAD_LIBRARIES |
		F_LOAD_TEMPLATES |
		F_VALIDATE_ARGS |
		F_ENABLE_ACCESSLOG
)

Configuration flags.

View Source
const (
	P_BASEPATH       = "basepath"
	P_EXTERNALURL    = "eternalurl"
	P_NAMESPACE      = "namespace"
	P_PUBLICDIR      = "pubdir"
	P_CONTEXT        = "context"
	P_LISTENADDR     = "addr"
	P_PUBLICCONTEXT  = "pubcontext"
	P_APPLICATIONKEY = "appkey"
	P_FLAGS          = "flags"
	P_COOKIENAME     = "cookie"
)

Identifier of initialization parameter

View Source
const (
	RelativeTemplatePath    = "templates"
	RelativeTemplateLibPath = "libs"
	HTTPTemplate            = "http.js"
	BindingTemplate         = "binding.js"
	InterfaceTemplate       = "interface.js"
	MethodTemplate          = "method.js"
	CTHeader                = "Content-Type"
	DefaultNamespace        = "GOTOJS"
	DefaultContext          = "/gotojs/"
	//DefaultEnginePath = "_engine.js"
	DefaultListenAddress     = "localhost:8080"
	DefaultFileServerDir     = "public"
	DefaultFileServerContext = "public"
	DefaultExternalBaseURL   = "http://" + DefaultListenAddress
	DefaultBasePath          = "."
	DefaultCookieName        = "gotojs"
	DefaultCookiePath        = "/"
	DefaultPlatform          = "web"
	DefaultMimeType          = "application/json"
	DefaultHeaderCRID        = "x-gotojs-crid"
	DefaultHeaderError       = "x-gotojs-error"
	DefaultProxyHeader       = "x-gotojs-proxy"
	DefaultCRID              = "undefined"
)

Internally used constants and default values

Variables

View Source
var Encoding = base64.NewEncoding("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_")

Cookie encoder. Standard encoder uses "=" symbol which is not allowed for cookies.

View Source
var Platforms = []string{"web", "nodejs"}

Functions

func ContainsS

func ContainsS(a []string, s string) bool

Check if a slice contains a certain string.

func ConvertTime

func ConvertTime(o interface{}) (ret time.Time, err error)

ConvertTime tries to convert an incoming interface to a local/native time object. Basically an order of formats will be tried here. Generally plain numbers are interpreted as unix timestamp in ms.

func Decrypt

func Decrypt(in, key []byte) []byte

decrypt decrypts an encrypted input string.

func Encrypt

func Encrypt(in, key []byte) []byte

encrypt encrypts an input string using the given key.

func Flag2Param

func Flag2Param(flag int) string

Flag2Param converts initialization flags to a string parameter.

func GenerateKey

func GenerateKey(size int) (ba []byte)

GenerateKey generates a random application key.

func Log

func Log(t string, args ...string)

Log is helper function that logs in various paremeter separated by a pipe in a standardized way.

func MapAppend

func MapAppend(to map[string]string, from map[string]string) map[string]string

MapAppend string parameter to a string parameter map.

func Minify

func Minify(c *http.Client, source []byte) []byte

Minify tries to cpmpile the given javascript source code using the google closure compiler. If the closure compiler failes it falls back to a pure go implementation.

func NewlogWrapper

func NewlogWrapper(origin http.Handler) *logWrapper

NewlogWrapper creates a new LogMuxer, that wraps the given http handler. See LogMuxer for more details.

func SAToIA

func SAToIA(args ...string) (ret []interface{})

sToIArray is an string var args to interface{} array converter.

func StringConverter

func StringConverter(o interface{}, t reflect.Type) (ret interface{}, err error)

String Converter tries to make a string out of the incoming object.

func TimeConverter

func TimeConverter(o interface{}, t reflect.Type) (ret interface{}, err error)

TimeConverter integrates the ConvertTime function as a converter.

Types

type Binary

type Binary interface {
	io.ReadCloser
	MimeType() string
}

Return interface which allows to return binary content with a specific mime type non json encoded

type BinaryBuffer

type BinaryBuffer struct {
	*bytes.Buffer
	// contains filtered or unexported fields
}

BinaryBuffer is an internal implementation to wrap a binary in a standard buffer object.

func NewBinaryBuffer

func NewBinaryBuffer(mt string) *BinaryBuffer

func (*BinaryBuffer) Close

func (b *BinaryBuffer) Close() error

func (*BinaryBuffer) MimeType

func (b *BinaryBuffer) MimeType() string

type BinaryContent

type BinaryContent struct{ *http.Request }

BinaryContent is an internal implementation to wrap a POST call as a Binary interface

func NewBinaryContent

func NewBinaryContent(req *http.Request) (ret *BinaryContent)

func (*BinaryContent) Close

func (b *BinaryContent) Close() error

func (*BinaryContent) MimeType

func (b *BinaryContent) MimeType() string

func (*BinaryContent) Read

func (b *BinaryContent) Read(p []byte) (n int, err error)

type Binding

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

Binding is a concrete method binding. It maps a interface and method name to a go object's method. The receiver is stored and in case of a method invocation, the original receiver will be passed while the method is called. Besides this the binding holds the information, which filter are active, which parameter needs to be injected by the InvokeI call or need to be registered as singletons..

func (Binding) AddInjection

func (b Binding) AddInjection(i interface{}) Binding

AddInjection adds a singleton injection object for the given binding and declares its type as injection object. It can also be used to declare a type and in the same step define a default singleton which will be injected in case no further object of this type will is provided for InvokeI calls.

func (Binding) ClearFilter

func (b Binding) ClearFilter() Binding

ClearFilter removes all filters for the given binding.

func (Binding) If

func (b Binding) If(f Filter) Binding

If sets a filter for the given binding. See type Filter for more information.

func (Binding) Invoke

func (b Binding) Invoke(args ...interface{}) (ret interface{})

Invoke a bound method or function with the given parameters.

func (Binding) InvokeI

func (b Binding) InvokeI(ri Injections, args ...interface{}) interface{}

InvokeI invokes the given binding and adds the binding itself as an injection.

func (Binding) Name

func (b Binding) Name() string

Name returns the name of the given Binding. This is a concatenation of the interface name, a "." seperator and the method name.

func (Binding) Remove

func (b Binding) Remove()

Remove removes the binding from the binding container.

func (Binding) S

func (b Binding) S() (ret Bindings)

S method returns an one element array of this binding.

func (Binding) Signature

func (b Binding) Signature() (ret string)

Signature returns a string representation of the binding signature.

func (Binding) Url

func (b Binding) Url() (ret *url.URL)

Url retrieves the actuall HTTP Url to access this binding directly.

func (Binding) ValidationString

func (b Binding) ValidationString() (ret string)

ValidationString generate a string that represents the signature of a method or function. It is used to perform a runtime validation when calling a JS proxy method.

type Bindings

type Bindings []Binding

Bindings is a list of concrete method bindings.

func (Bindings) AddInjection

func (bs Bindings) AddInjection(i interface{}) Bindings

AddInjection is a convenience method to AddInjection of type Binding.

func (Bindings) ClearFilter

func (bs Bindings) ClearFilter() Bindings

ClearFilter remove all filters from the given bindings.

func (Bindings) If

func (bs Bindings) If(f Filter) Bindings

If sets a filter for all given binding. See type Filter for more information.

func (Bindings) Invoke

func (r Bindings) Invoke(args ...interface{}) interface{}

Invoke the first bound method or function with the given parameters.

func (Bindings) InvokeI

func (r Bindings) InvokeI(inj Injections, args ...interface{}) interface{}

InvokeI the first bound method or function with the given parameters.

func (Bindings) Match

func (bs Bindings) Match(pattern string) Bindings

Match filters the list of Bindings and only returns those bindings whose name matches the given regex pattern. The interface is alwas placed in front of the method name seperated by a ".".

func (Bindings) Remove

func (bs Bindings) Remove()

Remove removes all bindings from their binding container.

type Container

type Container struct {
	*http.ServeMux //embed http muxer

	HTTPContextConstructor HTTPContextConstructor
	// contains filtered or unexported fields
}

Container represents a container which consists of a set of interfaces and their bindings.

Example (Binarycontent)
// Initialize the container.
container := NewContainer()

// Declare a Hello World handler function. The input parameter is taken from the POST body
// and passed as a "BinaryContent" object. The returned string will be JSON encoded.
container.ExposeFunction(func(bc *BinaryContent) string {
	defer bc.Close()
	b, _ := ioutil.ReadAll(bc)
	return string(b)
}, "main", "echo1")

//Declare a Hello World handler function. The response is directly passed to the ResponseWriter.
//The returning data is not anymore encoded as JSON.
container.ExposeFunction(func(bc *BinaryContent, hc *HTTPContext) {
	defer bc.Close()
	io.Copy(hc.Response, bc)
}, "main", "echo2")

// Start the server is separate go routine in parallel.
go func() { container.Start(":8793", "/gotojs") }()

time.Sleep(1 * time.Second) // Wait for the other go routine having the server up and running.

buf := bytes.NewBufferString("Hello Echo Server!")
dump(http.Post("http://localhost:8793/gotojs/main/echo1", "text/plain", buf))

buf = bytes.NewBufferString("This is not JSON!")
dump(http.Post("http://localhost:8793/gotojs/main/echo2", "text/plain", buf))
Output:

"Hello Echo Server!"
This is not JSON!
Example (Fileserver)
// Initialize the container.
container := NewContainer()

// Define the index.html and write it to the public dir:
index := `
<html>
 <head>
  <script src="gotojs/engine.js"></script>
 </head>
 <body><h1>Hello World !</h1></body>
</html>`

// Create a temporary file for testing purposes within the public fileserver directory.
b := bytes.NewBufferString(index)
err := ioutil.WriteFile("/tmp/__gotojs_index.html", b.Bytes(), 0644)
defer func() {
	// Clean up the temporary index.html
	os.Remove("/tmp/__gotojs_index.html")
}()
if err != nil {
	panic(err)
}

//Enable the fileserver wiht docroot at "/tmp" under path "p"
container.EnableFileServer("/tmp", "p")

//Create a redirect from homepage to the temporary index.html
container.Redirect("/", "/p/__gotojs_index.html")

// Start the server.
go func() { log.Fatal(container.Start("localhost:8789")) }()

time.Sleep(1 * time.Second) // Wait for the other go routine having the server up and running.

// Read the response and print it to the console.
resp, _ := http.Get("http://localhost:8789/")
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
fmt.Println(buf.String())
Output:

<html>
 <head>
  <script src="gotojs/engine.js"></script>
 </head>
 <body><h1>Hello World !</h1></body>
</html>
Example (Handlerbinding)
// Initialize the container.
container := NewContainer()

// Declare a Hello World handler function.
container.ExposeHandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Hello World! This data is not transformed into a JS object."))
}, "main", "hello")

// Declare a fake handler that always returns "404 page not found".
container.ExposeHandler(http.NotFoundHandler(), "main", "notfound")

// Start the server is separate go routine in parallel.
go func() { container.Start(":8792", "/gotojs") }()

time.Sleep(1 * time.Second) // Wait for the other go routine having the server up and running.
dump(http.Get("http://localhost:8792/gotojs/main/hello"))
dump(http.Get("http://localhost:8792/gotojs/main/notfound"))
Output:

Hello World! This data is not transformed into a JS object.
404 page not found
Example (Interface)
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

// Declare Service to be exposed.
type Service struct {
	name string
}

// Methods of Service that will be exposed.
func (s *Service) Hello(name string) string {
	return fmt.Sprintf("Hello %s, how are you ? Regards, %s.", name, s.name)
}

func main() {
	// Initialize the container.
	container := NewContainer()

	service := Service{name: "TestService"}

	// Expose the funcation and name it.
	container.ExposeInterface(service)

	// Start the server is seperate go routine in parallel.
	go func() { log.Fatal(container.Start("localhost:8790")) }()

	time.Sleep(1 * time.Second) // Wait for the other go routine having the server up and running.

	resp, _ := http.Get("http://localhost:8790/gotojs/Service/Hello/TestEngine")
	b, _ := ioutil.ReadAll(resp.Body)
	fmt.Println(string(b))

}
Output:

"Hello TestEngine, how are you ? Regards, TestService."
Example (Session)
// Initialize the container.
container := NewContainer()

// Declare a public login function.
login := func(session *Session, username, password string) string {
	if len(username) == len(password) { // trivial authentication  ;)
		session.Set("username", username)
		session.Set("authorized", "true")
		return "OK"
	} else {
		return "Invalid password."
	}
}

// Declare a private function callable.
private := func(session *Session, i string) string {
	return fmt.Sprintf("This is private %s of user %s", i, session.Get("username"))
}

//Expose all functions and name them:
container.ExposeFunction(login, "main", "login")
container.ExposeFunction(private, "main", "private").If(
	AutoInjectF(func(session *Session, c *HTTPContext) (b bool) {
		if b = session.Get("authorized") == "true"; !b {
			//Status code should be set to 403
			c.Response.WriteHeader(http.StatusForbidden)
		}
		return
	}))

// Start the server is separate go routine in parallel.
go func() { container.Start(":8791", "/gotojs") }()

time.Sleep(1 * time.Second)                    // Wait for the other go routine having the server up and running.
http.DefaultClient.Jar, _ = cookiejar.New(nil) // Cookie jar is needed here in order to associate session
// First call without previous login should result in a not authorized message.
dump(http.Get("http://localhost:8791/gotojs/main/private/TestData"))
// Second call has an invalid password
dump(http.Get("http://localhost:8791/gotojs/main/login/Alice/123456"))
// Third call is a correct login
dump(http.Get("http://localhost:8791/gotojs/main/login/Alice/12345"))
// Lat call is a successful request for private data.
dump(http.Get("http://localhost:8791/gotojs/main/private/TestData"))
http.DefaultClient.Jar = nil // Remove the cookie jar
Output:

"Invalid password."
"OK"
"This is private TestData of user Alice"
Example (Static)
// Initialize the container.
container := NewContainer()

// Define the content.
index := `
<html>
 <head>
  <script src="gotojs/engine.js"></script>
 </head>
 <body><h1>Hello World !</h1></body>
</html>`

// Assign the content to a path.
container.HandleStatic("/", index, "text/html")

// Start the server.
go func() { log.Fatal(container.Start("localhost:8788")) }()

time.Sleep(1 * time.Second) // Wait for the other go routine having the server up and running.

// Read the response and print it to the console.
resp, _ := http.Get("http://localhost:8788/")
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
fmt.Println(buf.String())
Output:

<html>
 <head>
  <script src="gotojs/engine.js"></script>
 </head>
 <body><h1>Hello World !</h1></body>
</html>

func NewContainer

func NewContainer(args ...Properties) *Container

NewContainer creates a new proxy container object. Required parameter are the configuration flags. Optional parameters are:

1) Namespace to be used

2) External URL the system is accessed

3) The base path where to look for template and library subdirectories func NewContainer(flags int,args ...string) (*Container){

func (*Container) BaseUrl

func (b *Container) BaseUrl() string

BaseUrl returns the eternal base url of the service. This may be a full qualified URL or just the path component.

func (Container) Binding

func (b Container) Binding(i string, mn string) (ret Binding, found bool)

Binding searches a concrete binding by the given interface and method name.

func (Container) BindingNames

func (b Container) BindingNames(i string) (methods []string)

BindingNames retreives all bound methods or functions names of the given interface.

func (Container) Bindings

func (b Container) Bindings() (ret Bindings)

Bindings returns all method bindings of the given container.

func (*Container) ClearCache

func (b *Container) ClearCache()

ClearCache clears the internally used cache. This also includes the engine code which needs to be reassembled afterwards. This happens on the next call that requests the engine.

func (*Container) Context

func (f *Container) Context(args ...string) string

Context gets or sets the gotojs path context. This path element defines how the engine code where the engine js code is served.

func (*Container) EnableFileServer

func (f *Container) EnableFileServer(args ...string)

EnableFileServer configures the file server and assigns the rooutes to the Multiplexer.

func (*Container) ExposeAllAttributes

func (b *Container) ExposeAllAttributes(i interface{}, name ...string) Bindings

ExposeAllAttributes is a convenience method to ExposeAttribute which exposes all public attributes of the given object.

func (*Container) ExposeAttributes

func (b *Container) ExposeAttributes(i interface{}, pattern string, name ...string) (ret Bindings)

ExposeAttributes exposes getter function to all public attributes of the given object.

func (*Container) ExposeFunction

func (b *Container) ExposeFunction(f interface{}, name ...string) Bindings

ExposeFunction exposes a single function. No receiver is required for this binding.

func (*Container) ExposeHandler

func (b *Container) ExposeHandler(v http.Handler, lin, lfn string) Bindings

ExposeHandler exposes an object which implements the http.Handler interface ServeHTTP.

func (*Container) ExposeHandlerFunc

func (b *Container) ExposeHandlerFunc(v http.HandlerFunc, lin, lfn string) Bindings

ExposeHandlerFunc exposes a raw handler function to the given interface and mathod name.

func (*Container) ExposeInterface

func (b *Container) ExposeInterface(i interface{}, name ...string) (ret Bindings)

Expose an entire interface. All methods of the given interface will be exposed. THe name of the exposed interface is either taken from type name or could be specified as additional name parameter.

func (*Container) ExposeMethod

func (b *Container) ExposeMethod(i interface{}, name string, target_name ...string) (ret Bindings)

ExposeMethod is a convenience method to ExposeMethods for exposing a single method of an interface.

func (*Container) ExposeMethods

func (b *Container) ExposeMethods(i interface{}, pattern string, name ...string) (ret Bindings)

ExposeMethods exposes the methods of a interface that do match the given regex pattern.

func (*Container) ExposeRemoteBinding

func (b *Container) ExposeRemoteBinding(u, rin, rmn, signature, lin, lfn string) Bindings

ExposeRemoteBinding ExposeRemoteBinding exposes a remote Binding by specifying the corresponding url. A proxy function will be installed that passes the binding request to the remote side.

func (*Container) ExposeYourself

func (b *Container) ExposeYourself(args ...string) (ret Bindings)

/ExposeYourself exposes some administrative and discovery methods of the gotojs container functionality.

func (*Container) Flags

func (b *Container) Flags(flags ...int) int

Flags gets and sets configuration flags. If method marameter are omitted, flags are just read from container object.

func (*Container) HandleStatic

func (f *Container) HandleStatic(pattern, content string, mime ...string)

HandleStatic is a convenience method which defines a static content handle that is assigned to the given path pattern. It allows to declare statically served content like HTML or JS snippets. The Content-Type can be optionally specified.

func (Container) Interface

func (b Container) Interface(name string) (ret Interface)

Interface is a convenience method to retrieve an interface. It panics if the interface does not exist.

func (Container) InterfaceNames

func (b Container) InterfaceNames() (keys []string)

InterfaceNames retrieves all bound interface names.

func (Container) Interfaces

func (b Container) Interfaces() (ret Interfaces)

Interfaces returns a list of all interface including its bindings.

func (Container) Invoke

func (b Container) Invoke(i, m string, args ...interface{}) interface{}

Invoke a bound method or function of the given interface and method name.

func (Container) InvokeI

func (b Container) InvokeI(i, m string, inj Injections, args ...interface{}) interface{}

InvokeI is a convenience method for invoking methods/function without prior discovery.

func (*Container) Redirect

func (f *Container) Redirect(pattern, url string)

Redirect is a convenience method which configures a redirect handler from the patter to adestination url.

func (Container) RegisterConverter

func (b Container) RegisterConverter(t interface{}, c Converter)

RegisterConverter defines the given converter function for the assigned type.

func (Container) RemoveBinding

func (b Container) RemoveBinding(i, m string)

RemoveBinding removes a single method from the binding container identified by the interface and method name.

func (Container) RemoveInterface

func (b Container) RemoveInterface(i string)

Remove an entire interface from the binding container identified by the interface name.

func (*Container) Setup

func (f *Container) Setup(args ...string) (handler http.Handler)

Setup creates and returns the final http handler for the container. It is called automatically by start, but if the container is used as an handler somewhere alse this setup method should be called instead. TODO: check what can be moved to initialization phase.

func (Container) SetupGlobalInjection

func (b Container) SetupGlobalInjection(i interface{})

SetupGlobaleIjection declares a type that will always be injected. This applies for both existing bindings as well as new bindings.

func (*Container) Start

func (f *Container) Start(args ...string) error

Start starts the http container. This method only returns in case a panic or unexpected error occurs. 1st optional parameter is the listen address ("localhost:8080") and 2nd optional parmaeter is the engine context ("/gotojs") If these are not provided, default or initialization values are used

type Converter

type Converter func(o interface{}, target reflect.Type) (interface{}, error)

Converter is a function type that converts a source object to a target type.

type Filter

type Filter func(Binding, Injections) bool

Filter is a filter function that receives, the binding which is currently being invoked and the Injection objects of the environment. It returns true if the call and filter chain may proceed. If it returns false, the request has been filtered or already answered and neither a further filter nor the real method call will be invoked.

func AutoInjectF

func AutoInjectF(f interface{}) Filter

AutoInjectF returns a filter function whose parameters will be automatically injected based on their types. Besides explicitly announced Injections by SetupInjection, both the *Binding as well as the full Injections container will be injected.

type HTTPContext

type HTTPContext struct {
	Client       *http.Client
	Request      *http.Request
	Response     http.ResponseWriter
	ErrorStatus  int
	ReturnStatus int
	Container    *Container
}

HTTPContext is a context object that will be injected by the container whenever an exposed method or function parameter is of type *HTTPContext. It contains references to all relevant http related objects like request and response object.

func NewHTTPContext

func NewHTTPContext(request *http.Request, response http.ResponseWriter) *HTTPContext

NewHTTPContext creates a new HTTP context based on incoming

func (*HTTPContext) CRID

func (c *HTTPContext) CRID() string

CRID returns the coreltation id if existing. Otherwise nil.

func (*HTTPContext) Errorf

func (c *HTTPContext) Errorf(status int, f string, args ...interface{})

Errorf sets the current HTTP context into an error state with the given status code and formated error message.

func (*HTTPContext) Session

func (c *HTTPContext) Session(key []byte) (s *Session)

Session tries to extract a session from the HTTPContext. If it cannot be extracted, a new session is created.

type HTTPContextConstructor

type HTTPContextConstructor func(*http.Request, http.ResponseWriter) *HTTPContext

type Injections

type Injections map[reflect.Type]interface{}

Injections is a container of injection objects sorted by their type.

func MergeInjections

func MergeInjections(inja ...Injections) (ret Injections)

MergeInjections merges multiple injections. The later ones overwrite the previous ones.

func NewI

func NewI(args ...interface{}) Injections

NewI constructs a new Injections container. Each parameter is part of the Injections container.

func (Injections) Add

func (inj Injections) Add(i interface{})

Add adds an injection object to the list of injections.

type Interface

type Interface map[string]Binding

Interface represents an interface binding which consists of a set of methods or functions.

func (Interface) Binding

func (i Interface) Binding(n string) (r Binding)

Binding is a convenience method to retrieve the method of a interface. It panics if the method does not exist.

func (Interface) Bindings

func (i Interface) Bindings() (ret Bindings)

Bindings returns all method bindings of the given container.

type Interfaces

type Interfaces []Interface

Interfaces represents a list or slice of Interfaces including all its bindings.

type Properties

type Properties map[string]string

Properties are generic string string maps used for a user session.

type ReaderArray

type ReaderArray []io.Reader

ReaderArray represents a vector of queued readers. Each reader will be consumed in order and closed if no bytes are read anymore.

func NewReaderArray

func NewReaderArray(r ...io.Reader) ReaderArray

NewReaderArray creates a new ReaderArray. It is an equivalent to default array constructor ReaderArray{...}. But this may change in the future with further functionality.

func (*ReaderArray) Add

func (r *ReaderArray) Add(rd io.Reader)

Add adds a Reader to the ReaderArray. It is an equivalent to readerArray = append(readerArray, rd)

func (ReaderArray) Close

func (r ReaderArray) Close() (err error)

Close closes all Reader of the ReaderArray.

func (ReaderArray) Read

func (r ReaderArray) Read(p []byte) (n int, err error)

Read reads successively from the ReaderArray.

type Session

type Session struct {
	Properties
	// contains filtered or unexported fields
}

Session represents a users session on server side. Basically it consists of a set of properties.

func NewSession

func NewSession() *Session

NewSession creates an empty fresh session object.

func SessionFromCookie

func SessionFromCookie(cookie *http.Cookie, key []byte) *Session

SessionFromCookie reads a session object from the cookie.

func (*Session) Cookie

func (s *Session) Cookie(name, path string, key []byte) *http.Cookie

Cookie generates a cookie object with the given name and path. the cookie value is taken from the session properties, json encoded, defalted, encrypted with the given key and finally base64 encoded.

func (*Session) Cookies

func (s *Session) Cookies(u *url.URL) []*http.Cookie

Cookies returns alls cookies that belong to this url. This can effectively be used as cookie proxy.

func (*Session) Delete

func (s *Session) Delete(key string)

Delete deletes the named property value if existing.

func (*Session) Flush

func (s *Session) Flush(w http.ResponseWriter, key []byte)

Flush updates the cookie on client side if it was changed. In order to do so it sets the "Set-Cookie" header on the http response

func (*Session) Get

func (s *Session) Get(key string) string

Get returns the named property value if existing. If not nil is returned.

func (*Session) Set

func (s *Session) Set(key, val string)

Set sets a property value with the given key.

func (*Session) SetCookies

func (s *Session) SetCookies(u *url.URL, cookies []*http.Cookie)

SetCookies wraps the cookies into this session. This can effectively be used as cookie proxy.

type Template

type Template struct {
	HTTP, Binding, Interface, Method string
	Libraries                        []string
}

Contains all loaded templates and references to external JS libraries.

type Templates

type Templates map[string]*Template

Templates per engine (web, nodejs) etc

func DefaultTemplates

func DefaultTemplates() (ret Templates)

DefaultTemplates returns the collection of internal Javascript templates for the generation of the JS engine.

Directories

Path Synopsis
Package gae offers a google appengine integration for the gotojs package.
Package gae offers a google appengine integration for the gotojs package.
Package stream of GOTOJS offers an interface to expose event or message streams.
Package stream of GOTOJS offers an interface to expose event or message streams.

Jump to

Keyboard shortcuts

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