gorest

package
v0.0.0-...-dd752a8 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2020 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

A RESTful style web-services framework for the Go language. </br> Creating services in Go is straight forward, GoRest? takes this a step further by adding a layer that makes tedious tasks much more automated and avoids regular pitfalls. <br/> This gives you the opportunity to focus more on the task at hand... minor low-level http handling.<br/>

Example usage below:

package main
import (
   "code.google.com/p/gorest"
        "http"
)
func main() {
    gorest.RegisterService(new(HelloService)) //Register our service
    http.Handle("/",gorest.Handle())
   http.ListenAndServe(":8787",nil)
}

//Service Definition
type HelloService struct {
    gorest.RestService `root:"/tutorial/"`
    helloWorld  gorest.EndPoint `method:"GET" path:"/hello-world/" output:"string"`
    sayHello    gorest.EndPoint `method:"GET" path:"/hello/{name:string}" output:"string"`
}
func(serv HelloService) HelloWorld() string{
   return "Hello World"
}
func(serv HelloService) SayHello(name string) string{
    return "Hello " + name
}

Index

Constants

View Source
const (
	XSXRF_COOKIE_NAME = "X-Xsrf-Cookie"
	XSXRF_PARAM_NAME  = "xsrft"
)
View Source
const (
	GET     = "GET"
	POST    = "POST"
	PUT     = "PUT"
	DELETE  = "DELETE"
	HEAD    = "HEAD"
	OPTIONS = "OPTIONS"
	PATCH   = "PATCH"
)
View Source
const (
	Application_ActiveMessage = "application/activemessage"
	Application_AppleFile     = "application/applefile"
	Application_AtomicMail    = "application/atomicmail"
	Application_MsWord        = "application/msword"
	Application_OctetStream   = "application/octet-stream"
	Application_Oda           = "application/oda"
	Application_Pdf           = "application/pdf"
	Application_PostScript    = "application/postscript"
	Application_Rtf           = "application/rtf"
	Application_Xml           = "application/xml"
	Application_Json          = "application/json"
	Application_Zip           = "application/zip"
	Audio_Xaiff               = "audio/x-aiff"
	Audio_Xwav                = "audio/x-wav"
	Image_Cgm                 = "image/cgm"
	Image_G3Fax               = "image/g3fax"
	Image_Gif                 = "image/gif"
	Image_Ief                 = "image/ief"
	Image_Jpeg                = "image/jpeg"
	Image_Naplps              = "image/naplps"
	Image_Png                 = "image/png"
	Image_Tiff                = "image/tiff"
	Multipart_Alternative     = "multipart/alternative"
	Multipart_AppleDouble     = "multipart/appledouble"
	Multipart_Digest          = "multipart/digest"
	Multipart_FormData        = "multipart/form-data"
	Multipart_HeaderSet       = "multipart/header-set"
	Multipart_Mixed           = "multipart/mixed"
	Multipart_Parallel        = "multipart/parallel"
	Multipart_Related         = "multipart/related"
	Multipart_Report          = "multipart/report"
	Multipart_VoiceMessage    = "multipart/voice-message"
	Text_Enriched             = "text/enriched"
	Text_Html                 = "text/html"
	Text_Plain                = "text/plain"
	Text_RichText             = "text/richtext"
	Text_Sgml                 = "text/sgml"
	Text_TabSeparatedValues   = "text/tab-separated-values"
	Text_Xml                  = "text/xml"
	Text_X_SeText             = "text/x-setext"
	Video_Mpeg                = "video/mpeg"
	Video_Quicktime           = "video/quicktime"
	Video_VndVivo             = "video/vnd.vivo"
	Video_VndMotorolaVideo    = "video/vnd.motorola.video"
	Video_VndMotorolaVideoP   = "video/vnd.motorola.videop"
	Video_X_MS_Video          = "video/x-msvideo"
	Video_X_SgiMovie          = "video/x-sgi-movie"
)
View Source
const (
	ERROR_INVALID_INTERFACE = "" /* 149-byte string literal not displayed */
)

Variables

This section is empty.

Functions

func BytesToInterface

func BytesToInterface(buf *bytes.Buffer, i interface{}, mime string) error

func Handle

func Handle() manager

func HandleFunc

func HandleFunc(w http.ResponseWriter, r *http.Request)

Registeres the function to be used for handling all requests directed to gorest.

func InterfaceToBytes

func InterfaceToBytes(i interface{}, mime string) ([]byte, error)

Marshals the data in interface i into a byte slice, using the Marhaller/Unmarshaller specified in mime. The Marhaller/Unmarshaller must have been registered before using gorest.RegisterMarshaller

func Marshal

func Marshal(i interface{}, mime string) ([]byte, error)

Marshals the data in interface i into a byte slice, using the Marhaller/Unmarshaller specified in mime. The Marhaller/Unmarshaller must have been registered before using gorest.RegisterMarshaller

func RegisterMarshaller

func RegisterMarshaller(mime string, m *Marshaller)

Register a Marshaller. These registered Marshallers are shared by the client or servers side usage of gorest.

func RegisterRealmAuthorizer

func RegisterRealmAuthorizer(realm string, auth Authorizer)

Registers an Authorizer for the specified realm.

func RegisterService

func RegisterService(h interface{})

Registeres a service on the rootpath. See example below:

package main
import (
   "code.google.com/p/gorest"
        "http"
)
func main() {
    gorest.RegisterService(new(HelloService)) //Register our service
    http.Handle("/",gorest.Handle())
   http.ListenAndServe(":8787",nil)
}

//Service Definition
type HelloService struct {
    gorest.RestService `root:"/tutorial/"`
    helloWorld  gorest.EndPoint `method:"GET" path:"/hello-world/" output:"string"`
    sayHello    gorest.EndPoint `method:"GET" path:"/hello/{name:string}" output:"string"`
}
func(serv HelloService) HelloWorld() string{
   return "Hello World"
}
func(serv HelloService) SayHello(name string) string{
    return "Hello " + name
}

func RegisterServiceOnPath

func RegisterServiceOnPath(root string, h interface{})

Registeres a service under the specified path. See example below:

package main
import (
    "code.google.com/p/gorest"
        "http"
)
func main() {
    gorest.RegisterServiceOnPath("/rest/",new(HelloService)) //Register our service
    http.Handle("/",gorest.Handle())
    http.ListenAndServe(":8787",nil)
}

//Service Definition
type HelloService struct {
    gorest.RestService `root:"/tutorial/"`
    helloWorld  gorest.EndPoint `method:"GET" path:"/hello-world/" output:"string"`
    sayHello    gorest.EndPoint `method:"GET" path:"/hello/{name:string}" output:"string"`
}
func(serv HelloService) HelloWorld() string{
    return "Hello World"
}
func(serv HelloService) SayHello(name string) string{
    return "Hello " + name
}

func ServeStandAlone

func ServeStandAlone(port int)

Runs the default "net/http" DefaultServeMux on the specified port. All requests are handled using gorest.HandleFunc()

func Unmarshal

func Unmarshal(buf *bytes.Buffer, i interface{}, mime string) error

Unmarshals the data in buf into interface i, using the Marhaller/Unmarshaller specified in mime. The Marhaller/Unmarshaller must have been registered before using gorest.RegisterMarshaller

Types

type Authorizer

type Authorizer func(string, string) (bool, bool, SessionData)

Signiture of functions to be used as Authorizers

func GetAuthorizer

func GetAuthorizer(realm string) (a Authorizer)

Returns the registred Authorizer for the specified realm.

type Context

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

func (*Context) Request

func (c *Context) Request() *http.Request

Returns a *http.Request associated with this Context

type EndPoint

type EndPoint bool

Used to declare and EndPoint, wich represents a single point of entry to gorest applications, via a URL. See code example below:

type HelloService struct {
    gorest.RestService `root:"/tutorial/"`
   helloWorld  gorest.EndPoint `method:"GET" path:"/hello-world/" output:"string"`
   sayHello    gorest.EndPoint `method:"GET" path:"/hello/{name:string}" output:"string"`
}

type GoRestService

type GoRestService interface {
	ResponseBuilder() *ResponseBuilder
}

type Marshaller

type Marshaller struct {
	Marshal   func(v interface{}) ([]byte, error)
	Unmarshal func(data []byte, v interface{}) error
}

A Marshaller represents the two functions used to marshal/unmarshal interfaces back and forth.

func GetMarshallerByMime

func GetMarshallerByMime(mime string) (m *Marshaller)

Get an already registered Marshaller

func NewJSONMarshaller

func NewJSONMarshaller() *Marshaller

JSON: This makes the JSON Marshaller. The Marshaller uses pkg: json

func NewXMLMarshaller

func NewXMLMarshaller() *Marshaller

XML

type RequestBuilder

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

func NewRequestBuilder

func NewRequestBuilder(url string) (*RequestBuilder, error)

This creates a new RequestBuilder, backed by GoRest's internally managed http.Client. Although http.Client is useable concurrently, an instance of RequestBuilder is not safe for this. Because of http.Client's persistent(cached TCP connections) and concurrent nature, this can be used safely multiple times from different go routines.

func NewRequestBuilderFromClient

func NewRequestBuilderFromClient(client *http.Client, url string) (*RequestBuilder, error)

Use this if you have a *http.Client instance that you specifically want to use. Otherwise just use NewRequestBuilder(), which uses the http.Client maintained by GoRest.

func (*RequestBuilder) Accept

func (this *RequestBuilder) Accept(mime string) *RequestBuilder

func (*RequestBuilder) AcceptCharSet

func (this *RequestBuilder) AcceptCharSet(set string) *RequestBuilder

func (*RequestBuilder) AcceptCharSetClear

func (this *RequestBuilder) AcceptCharSetClear() *RequestBuilder

func (*RequestBuilder) AcceptClear

func (this *RequestBuilder) AcceptClear() *RequestBuilder

func (*RequestBuilder) AcceptEncoding

func (this *RequestBuilder) AcceptEncoding(option string) *RequestBuilder

func (*RequestBuilder) AcceptEncodingClear

func (this *RequestBuilder) AcceptEncodingClear() *RequestBuilder

func (*RequestBuilder) AcceptLanguage

func (this *RequestBuilder) AcceptLanguage(lang string) *RequestBuilder

func (*RequestBuilder) AcceptLanguageClear

func (this *RequestBuilder) AcceptLanguageClear() *RequestBuilder

func (*RequestBuilder) AddCookie

func (this *RequestBuilder) AddCookie(cookie *http.Cookie) *RequestBuilder

func (*RequestBuilder) CacheClearAllOptions

func (this *RequestBuilder) CacheClearAllOptions() *RequestBuilder

func (*RequestBuilder) CacheMaxAge

func (this *RequestBuilder) CacheMaxAge(seconds int) *RequestBuilder

func (*RequestBuilder) CacheMinFresh

func (this *RequestBuilder) CacheMinFresh(seconds int) *RequestBuilder

func (*RequestBuilder) CacheNoCache

func (this *RequestBuilder) CacheNoCache() *RequestBuilder

func (*RequestBuilder) CacheNoStore

func (this *RequestBuilder) CacheNoStore() *RequestBuilder

func (*RequestBuilder) CacheOnlyIfCached

func (this *RequestBuilder) CacheOnlyIfCached() *RequestBuilder

func (*RequestBuilder) CacheStale

func (this *RequestBuilder) CacheStale(seconds int) *RequestBuilder

func (*RequestBuilder) ConnectionClose

func (this *RequestBuilder) ConnectionClose() *RequestBuilder

func (*RequestBuilder) ConnectionKeepAlive

func (this *RequestBuilder) ConnectionKeepAlive() *RequestBuilder

func (*RequestBuilder) Delete

func (this *RequestBuilder) Delete() (*http.Response, error)

func (*RequestBuilder) Get

func (this *RequestBuilder) Get(i interface{}, expecting int) (*http.Response, error)

func (*RequestBuilder) Head

func (this *RequestBuilder) Head() (*http.Response, error)

func (*RequestBuilder) Options

func (this *RequestBuilder) Options(opts *[]string) (*http.Response, error)

func (*RequestBuilder) Post

func (this *RequestBuilder) Post(i interface{}) (*http.Response, error)

func (*RequestBuilder) Request

func (this *RequestBuilder) Request() *http.Request

func (*RequestBuilder) UseContentType

func (this *RequestBuilder) UseContentType(mime string) *RequestBuilder

type ResponseBuilder

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

Facilitates the construction of the response to be sent to the client.

func (*ResponseBuilder) AddHeader

func (this *ResponseBuilder) AddHeader(key string, value string) *ResponseBuilder

Used to add gereric/custom headers to the response. Good use for proxying and cross origins/site stuff. Example usage:

rb := serv.ResponseBuilder()
rb.AddHeader("Access-Control-Allow-Origin","http://127.0.0.1:8888")
rb.AddHeader("Access-Control-Allow-Headers","X-HTTP-Method-Override")
rb.AddHeader("Access-Control-Allow-Headers","X-Xsrf-Cookie")
rb.AddHeader("Access-Control-Expose-Headers","X-Xsrf-Cookie")

func (*ResponseBuilder) Age

func (this *ResponseBuilder) Age(seconds int) *ResponseBuilder

func (*ResponseBuilder) Allow

func (this *ResponseBuilder) Allow(tag string) *ResponseBuilder

Add an "Allow" field to the response header.

func (*ResponseBuilder) CacheClearAllOptions

func (this *ResponseBuilder) CacheClearAllOptions() *ResponseBuilder

Delete/clear all Cache-control options from the response header.

func (*ResponseBuilder) CacheMaxAge

func (this *ResponseBuilder) CacheMaxAge(seconds int) *ResponseBuilder

Add a "Cache-control" field of "max-age = ?" to the response header.

func (*ResponseBuilder) CacheMustReval

func (this *ResponseBuilder) CacheMustReval() *ResponseBuilder

Add a "Cache-control" field of "must-revalidate" to the response header.

func (*ResponseBuilder) CacheNoCache

func (this *ResponseBuilder) CacheNoCache() *ResponseBuilder

Add a "Cache-control" field of "no-cache" to the response header.

func (*ResponseBuilder) CacheNoStore

func (this *ResponseBuilder) CacheNoStore() *ResponseBuilder

Add a "Cache-control" field of "no-store" to the response header.

func (*ResponseBuilder) CacheNoTransform

func (this *ResponseBuilder) CacheNoTransform() *ResponseBuilder

Add a "Cache-control" field of "no-transform" to the response header.

func (*ResponseBuilder) CachePrivate

func (this *ResponseBuilder) CachePrivate() *ResponseBuilder

Add a "Cache-control" field of "private" to the response header.

func (*ResponseBuilder) CacheProxyReval

func (this *ResponseBuilder) CacheProxyReval() *ResponseBuilder

Add a "Cache-control" field of "proxy-revalidate" to the response header.

func (*ResponseBuilder) CachePublic

func (this *ResponseBuilder) CachePublic() *ResponseBuilder

Add a "Cache-control" field of "public" to the response header.

func (*ResponseBuilder) CacheSMaxAge

func (this *ResponseBuilder) CacheSMaxAge(seconds int) *ResponseBuilder

Add a "Cache-control" field of "s-maxage = ?" to the response header.

func (*ResponseBuilder) ConnectionClose

func (this *ResponseBuilder) ConnectionClose() *ResponseBuilder

Set a "Connection" field of "close" to the response header.

func (*ResponseBuilder) ConnectionKeepAlive

func (this *ResponseBuilder) ConnectionKeepAlive() *ResponseBuilder

Set a "Connection" field of "keep-alive" to the response header.

func (*ResponseBuilder) Created

func (this *ResponseBuilder) Created(location string) *ResponseBuilder

Set a "Location" field of "??" and set the responseCode to 201, to the response header.

func (*ResponseBuilder) DelHeader

func (this *ResponseBuilder) DelHeader(key string) *ResponseBuilder

func (*ResponseBuilder) ETag

func (this *ResponseBuilder) ETag(tag string) *ResponseBuilder

Set "Etag" to the resopnse.

func (*ResponseBuilder) Found

func (this *ResponseBuilder) Found(location string) *ResponseBuilder

Set a "Location" field of "??" and set the responseCode to 302, to the response header.

func (*ResponseBuilder) Location

func (this *ResponseBuilder) Location(location string) *ResponseBuilder

Set a "Location" field of "??" to the response header.

func (*ResponseBuilder) LongPoll

func (this *ResponseBuilder) LongPoll(delay int, producer func(interface{}) interface{}) *ResponseBuilder

func (*ResponseBuilder) MovedPermanently

func (this *ResponseBuilder) MovedPermanently(location string) *ResponseBuilder

Set a "Location" field of "??" and set the responseCode to 301, to the response header.

func (*ResponseBuilder) MovedTemporarily

func (this *ResponseBuilder) MovedTemporarily(location string) *ResponseBuilder

Set a "Location" field of "??" and set the responseCode to 307, to the response header.

func (*ResponseBuilder) Overide

func (this *ResponseBuilder) Overide(overide bool)

This indicates whether the data returned by the endpoint service method should be ignored or appendend to the data already writen to the response via ResponseBuilder. A vlaue of "true" will discard, while a value of "false"" will append.

func (*ResponseBuilder) RemoveSessionToken

func (this *ResponseBuilder) RemoveSessionToken(path string)

This cleares the "xsrftoken" token associated with the current request and hence session. Calling this will unlink the current session, making it un-addressable/invalid. Therefore if maintaining a session store you may want to evict/destroy the session there.

func (*ResponseBuilder) SeeOther

func (this *ResponseBuilder) SeeOther(location string) *ResponseBuilder

Set a "Location" field of "??" and set the responseCode to 303, to the response header.

func (*ResponseBuilder) SessionToken

func (this *ResponseBuilder) SessionToken() string

Returns the "xsrftoken" token associated with the current request and hence session. This token is either passed vi a URL query parameter "xsrft=1234567" or via a cookie with the name "X-Xsrf-Cookie", all depending on how your Authoriser is set up.

func (*ResponseBuilder) SetContentType

func (this *ResponseBuilder) SetContentType(mime string) *ResponseBuilder

Set the content type of the http entity that is to be sent to the client.

func (*ResponseBuilder) SetHeader

func (this *ResponseBuilder) SetHeader(key string, value string) *ResponseBuilder

func (*ResponseBuilder) SetResponseCode

func (this *ResponseBuilder) SetResponseCode(code int) *ResponseBuilder

Set the http code to be sent with the response, to the client.

func (*ResponseBuilder) SetSessionToken

func (this *ResponseBuilder) SetSessionToken(token string, path string, expires time.Time)

Sets the "xsrftoken" token associated with the current request and hence session, only valid for the sepcified root path and period. This creates a cookie and sets an http header with the name "X-Xsrf-Cookie"

func (*ResponseBuilder) Write

func (this *ResponseBuilder) Write(data []byte) *ResponseBuilder

This will just write to the response without affecting the change done by a call to Overide().

func (*ResponseBuilder) WriteAndContinue

func (this *ResponseBuilder) WriteAndContinue(data []byte) *ResponseBuilder

This will write to the response and then call Overide(false), even if it had been set to "true" in a previous call.

func (*ResponseBuilder) WriteAndOveride

func (this *ResponseBuilder) WriteAndOveride(data []byte) *ResponseBuilder

This will write to the response and then call Overide(true), even if it had been set to "false" in a previous call.

type RestService

type RestService struct {
	Context *Context
	// contains filtered or unexported fields
}

Used to declare a new service. See code example below:

type HelloService struct {
    gorest.RestService `root:"/tutorial/"`
    helloWorld  gorest.EndPoint `method:"GET" path:"/hello-world/" output:"string"`
    sayHello    gorest.EndPoint `method:"GET" path:"/hello/{name:string}" output:"string"`
}

func (RestService) RB

func (serv RestService) RB() *ResponseBuilder

Returns the ResponseBuilder associated with the current Context and Request. This can be called multiple times within a service method, the same instance will be returned.

func (RestService) ResponseBuilder

func (serv RestService) ResponseBuilder() *ResponseBuilder

Returns the ResponseBuilder associated with the current Context and Request. This can be called multiple times within a service method, the same instance will be returned.

func (RestService) Session

func (serv RestService) Session() SessionData

Get the SessionData associated with the current request, as sotred in the Context.

type SessionData

type SessionData interface {
	SessionId() string
}

Interface to be implemented by any session storage mechanism to be used with authorization.

func DefaultAuthorizer

func DefaultAuthorizer(id string, role string) (bool, bool, SessionData)

This is the default and exmaple authorizer that is used to authorize requests to endpints with no security realms. It always allows access and returns nil for SessionData.

Jump to

Keyboard shortcuts

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