hprose

package module
v1.5.1 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2015 License: MIT Imports: 25 Imported by: 0

README

Hprose for Golang

Build Status GoDoc



Introduction

Hprose is a High Performance Remote Object Service Engine.

It is a modern, lightweight, cross-language, cross-platform, object-oriented, high performance, remote dynamic communication middleware. It is not only easy to use, but powerful. You just need a little time to learn, then you can use it to easily construct cross language cross platform distributed application system.

Hprose supports many programming languages, for example:

  • AAuto Quicker
  • ActionScript
  • ASP
  • C++
  • Dart
  • Delphi/Free Pascal
  • dotNET(C#, Visual Basic...)
  • Golang
  • Java
  • JavaScript
  • Node.js
  • Objective-C
  • Perl
  • PHP
  • Python
  • Ruby
  • ...

Through Hprose, You can conveniently and efficiently intercommunicate between those programming languages.

This project is the implementation of Hprose for Golang.

Installation

go get github.com/hprose/hprose-go
go install github.com/hprose/hprose-go

Usage

Http Server

Hprose for Golang is very easy to use. You can create a hprose http server like this:

package main

import (
	"errors"
	"github.com/hprose/hprose-go"
	"net/http"
)

func hello(name string) string {
	return "Hello " + name + "!"
}

type myService struct{}

func (myService) Swap(a int, b int) (int, int) {
	return b, a
}

func (myService) Sum(args ...int) (int, error) {
	if len(args) < 2 {
		return 0, errors.New("Requires at least two parameters")
	}
	a := args[0]
	for i := 1; i < len(args); i++ {
		a += args[i]
	}
	return a, nil
}

func main() {
	service := hprose.NewHttpService()
	service.AddFunction("hello", hello)
	service.AddMethods(myService{})
	http.ListenAndServe(":8080", service)
}

You can publish multi-valued functions/methods, the multi-valued result will be automatically converted to an array result.

Http Client
Synchronous Invoking

Then you can create a hprose http client to invoke it like this:

package main

import (
	"fmt"
	"github.com/hprose/hprose-go"
)

type clientStub struct {
	Hello func(string) string
	Swap  func(int, int) (int, int)
	Sum   func(...int) (int, error)
}

func main() {
	client := hprose.NewClient("http://127.0.0.1:8080/")
	var ro *clientStub
	client.UseService(&ro)
	fmt.Println(ro.Hello("World"))
	fmt.Println(ro.Swap(1, 2))
	fmt.Println(ro.Sum(1, 2, 3, 4, 5))
	fmt.Println(ro.Sum(1))
}
Synchronous Exception Handling

Client stubs do not have exactly the same with the server-side interfaces. For example:

package main

import (
	"fmt"
	"github.com/hprose/hprose-go"
)

type clientStub struct {
	Sum   func(...int) int
}

func main() {
	client := hprose.NewClient("http://127.0.0.1:8080/")
	var ro *clientStub
	client.UseService(&ro)
	fmt.Println(ro.Sum(1, 2, 3, 4, 5))
	fmt.Println(ro.Sum(1))
}

If an error (must be the last out parameter) returned by server-side function/method, or it panics in the server-side, the client will receive it. If the client stub has an error out parameter (also must be the last one), you can get the server-side error or panic from it. If the client stub have not define an error out parameter, the client stub will panic when receive the server-side error or panic.

Asynchronous Invoking

Hprose for golang supports golang style asynchronous invoke. It does not require a callback function, but need to define the channel out parameters. for example:

package main

import (
	"fmt"
	"github.com/hprose/hprose-go"
)

type clientStub struct {
	Sum func(...int) (<-chan int, <-chan error)
}

func main() {
	client := hprose.NewClient("http://127.0.0.1:8080/")
	var ro *clientStub
	client.UseService(&ro)
	sum, err := ro.Sum(1, 2, 3, 4, 5)
	fmt.Println(<-sum, <-err)
	sum, err = ro.Sum(1)
	fmt.Println(<-sum, <-err)
}
Asynchronous Exception Handling

When using asynchronous invoking, you need to define a <-chan error out parameter (also the last one) to receive the server-side error or panic (or exception in other languages). If you omit this parameter, the client will ignore the exception, like never happened.

For example:

package main

import (
    "fmt"
    "github.com/hprose/hprose-go"
)

type clientStub struct {
    Sum func(...int) (<-chan int)
}

func main() {
    client := hprose.NewClient("http://127.0.0.1:8080/")
    var ro *clientStub
    client.UseService(&ro)
    fmt.Println(<-ro.Sum(1))
}

You will get the result 0, but do not know what happened.

Function Alias

Golang does not support function/method overload, but some other languages support. So hprose provides "Function/Method Alias" to invoke overloaded methods in other languages. You can also use it to invoke the same function/method with different names.

For example:

package main

import (
    "fmt"
    "github.com/hprose/hprose-go"
)

type clientStub struct {
    Hello      func(string) string
    AsyncHello func(string) <-chan string `name:"hello"`
}

func main() {
    client := hprose.NewClient("http://127.0.0.1:8080/")
    var ro *clientStub
    client.UseService(&ro)
    fmt.Println(ro.Hello("Synchronous Invoking"))
    fmt.Println(<-ro.AsyncHello("Asynchronous Invoking"))
}

The real remote function/method name is specified in the function field tag.

Passing by reference parameters

Hprose supports passing by reference parameters. The parameters must be pointer types. Open this option also in the function field tag. For example:

package main

import (
    "fmt"
    "github.com/hprose/hprose-go"
)

type clientStub struct {
    Swap func(*map[string]string) `name:"swapKeyAndValue" byref:"true"`
}

func main() {
    client := hprose.NewClient("http://hprose.com/example/")
    var ro *clientStub
    client.UseService(&ro)
    m := map[string]string{
        "Jan": "January",
        "Feb": "February",
        "Mar": "March",
        "Apr": "April",
        "May": "May",
        "Jun": "June",
        "Jul": "July",
        "Aug": "August",
        "Sep": "September",
        "Oct": "October",
        "Nov": "November",
        "Dec": "December",
    }
    fmt.Println(m)
    ro.Swap(&m)
    fmt.Println(m)
}

The server of this example was written in PHP. In fact, You can use any language which hprose supported to write the server.

Custom Struct

You can transfer custom struct objects between hprose client and hprose server directly.

Using the ClassManager.Register method to register your custom struct is the the only thing you need to do. For example:

package main

import (
    "fmt"
    "github.com/hprose/hprose-go"
)

type TestUser struct {
    Name     string
    Sex      int
    Birthday time.Time
    Age      int
    Married  bool
}

type remoteObject struct {
    GetUserList         func() []TestUser
}

func main() {
    ClassManager.Register(reflect.TypeOf(TestUser{}), "User")
    client := NewClient("http://www.hprose.com/example/")
    var ro *remoteObject
    client.UseService(&ro)

    fmt.Println(ro.GetUserList())
}

The first argument of ClassManager.Register is the type of your custom struct. The second argument is the alias of your custom struct.

The real name of your custom struct can be different between the client and the server, as long as they registered the same alias.

The server of this example was written in PHP. In fact, You can use custom struct with go server too.

Field Alias of Custom Struct

The first letter of the field name will be lowercased automatically when it is serialized. So we don't need to define a tag to implement this feature like Json serialization when we interact with the other languages.

But it doesn't mean that hprose can't support to define field alias by tag. In fact, it can not only, and it can be compatible with the field alias definition in Json serialization way. For example:

...
type User struct {
	Name string `json:"n"`
	Age  int    `json:"a"`
	OOXX string `json:"-"`
}
...
hprose.ClassManager.Register(reflect.TypeOf(User{}), "User", "json")
...

The struct above is defined for Json serialization. But when we called ClassManager.Register by passing the third argument "json", we can use the fields aliases defined in json tags for hprose serialization. If the field alias is "-", it will be not serialized.

You can change the json tag to be anything else in the struct definition, such as hprose, as long as it is the same with the value of the ClassManager.Register third argument.

Hprose Proxy

You can use hprose server and client to create a hprose proxy server. All requests sent to the hprose proxy server will be forwarded to the backend hprose server. For example:

package main

import (
    "github.com/hprose/hprose-go"
    "net/http"
)

type proxyStub struct {
    Hello func(string) (string, error)
    Swap  func(int, int) (int, int)
    Sum   func(...int) (int)
}

func main() {
    client := hprose.NewClient("http://127.0.0.1:8080/")
    var ro *proxyStub
    client.UseService(&ro)
    service := hprose.NewHttpService()
    service.AddMethods(ro)
    http.ListenAndServe(":8181", service)
}

Whether the definition of the error out parameter does not matter, the exception will be automatically forwarded.

Better Proxy

Hprose provides an ResultMode options to improve performance of the proxy server. You can use it like this:

package main

import (
    "github.com/hprose/hprose-go"
    "net/http"
)

type proxyStub struct {
    Hello func(string) []byte   `result:"raw"`
    Swap  func(int, int) []byte `result:"raw"`
    Sum   func(...int) []byte   `result:"raw"`
}

func main() {
    client := hprose.NewClient("http://127.0.0.1:8080/")
    var ro *proxyStub
    client.UseService(&ro)
    service := hprose.NewHttpService()
    service.AddMethods(ro, hprose.Raw)
    http.ListenAndServe(":8181", service)
}

The client result mode option is setting in the func field tag, and the return value must be []byte. The server result mode option is setting by AddMethods parameter.

The ResultMode have 4 values:

  • Normal
  • Serialized
  • Raw
  • RawWithEndTag

The Normal result mode is the default value.

In Serialized result mode, the returned value is a hprose serialized data in []byte, but the arguments and exception will be parsed to the normal value.

In Raw result mode, all the reply will be returned directly to the result in []byte, but the result data doesn't have the hprose end tag.

The RawWithEndTag is similar to the Raw result mode, but it has the hprose end tag.

With the ResultMode option, you can store, cache and forward the result in the original format.

Simple Mode

By default, the data between the hprose client and server can be passed with internal references. if your data have no internal references, you can open the simple mode to improve performance.

You can open simple mode in server like this:

package main

import (
    "github.com/hprose/hprose-go"
    "net/http"
)

func hello(name string) string {
    return "Hello " + name + "!"
}

func main() {
    service := hprose.NewHttpService()
    service.AddFunction("hello", hello, true)
    http.ListenAndServe(":8080", service)
}

The option parameter true is the simple mode switch. The result will be transmitted to the client in simple mode when it is on.

To open the client simple mode is like this:

package main

import (
    "fmt"
    "github.com/hprose/hprose-go"
)

type clientStub struct {
    Hello func(string) string       `simple:"true"`
    Swap  func(int, int) (int, int) `simple:"true"`
    Sum   func(...int) (int, error)
}

func main() {
    client := hprose.NewClient("http://127.0.0.1:8181/")
    var ro *clientStub
    client.UseService(&ro)
    fmt.Println(ro.Hello("World"))
    fmt.Println(ro.Swap(1, 2))
    fmt.Println(ro.Sum(1, 2, 3, 4, 5))
    fmt.Println(ro.Sum(1))
}

The arguments will be transmitted to the server in simple mode when it is on.

Missing Method

Hprose supports publishing a special method: MissingMethod. All methods not explicitly published will be redirected to the method. For example:

package main

import (
    "github.com/hprose/hprose-go"
    "net/http"
    "reflect"
    "strings"
)

func hello(name string) string {
    return "Hello " + name + "!"
}

func missing(name string, args []reflect.Value) (result []reflect.Value) {
    result = make([]reflect.Value, 1)
    switch strings.ToLower(name) {
    case "add":
        result[0] = reflect.ValueOf(args[0].Interface().(int) + args[1].Interface().(int))
    case "sub":
        result[0] = reflect.ValueOf(args[0].Interface().(int) - args[1].Interface().(int))
    case "mul":
        result[0] = reflect.ValueOf(args[0].Interface().(int) * args[1].Interface().(int))
    case "div":
        result[0] = reflect.ValueOf(args[0].Interface().(int) / args[1].Interface().(int))
    default:
        panic("The method '" + name + "' is not implemented.")
    }
    return
}

func main() {
    service := hprose.NewHttpService()
    service.AddFunction("hello", hello, true)
    service.AddMissingMethod(missing, true)
    http.ListenAndServe(":8080", service)
}

If you want return an error to the client, please use panic. The error type return value can't be processed in the method.

The simple mode and the result mode options can also be used with it.

Invoking the missing method makes no difference with the normal method. For example:

package main

import (
    "fmt"
    "github.com/hprose/hprose-go"
)

type clientStub struct {
    Add   func(int, int) int
    Sub   func(int, int) int
    Mul   func(int, int) int
    Div   func(int, int) int
    Power func(int, int) (int, error)
}

func main() {
    client := hprose.NewClient("http://127.0.0.1:8080/")
    var ro *clientStub
    client.UseService(&ro)
    fmt.Println(ro.Add(1, 2))
    fmt.Println(ro.Sub(1, 2))
    fmt.Println(ro.Mul(1, 2))
    fmt.Println(ro.Div(1, 2))
    fmt.Println(ro.Power(1, 2))
}

The result is:

3
-1
2
0
0 The method 'Power' is not implemented.
TCP Server and Client

Hprose for Golang supports TCP Server and Client. It is very easy to use like the HTTP Server and Client.

To create a hprose TCP server, you can use NewTcpService or NewTcpServer.

To use NewTcpService, you need call the ServeTCP method and passing the TCP Connection to it.

using NewTcpServer is easier than NewTcpService. For example:

    ...
    server := hprose.NewTcpServer("tcp://127.0.0.1:1234/")
    server.AddFunction("hello", hello)
    server.Start()
    ...

To create a hprose TCP client is the same as HTTP client:

    ...
    client := hprose.NewClient("tcp://127.0.0.1:1234/")
    ...

You can also specify tcp4:// scheme to using ipv4 or tcp6:// scheme to using ipv6.

Unix Server and Client

Hprose for Golang supports Unix Socket Server and Client. It is very easy to use like the Tcp Server and Client.

To create a hprose Unix server, you can use NewUnixService or NewUnixServer.

To use NewUnixService, you need call the ServeUnix method and passing the Unix Connection to it.

using NewUnixServer is easier than NewUserService. For example:

    ...
    server := hprose.NewUnixServer("unix:/tmp/my.sock")
    server.AddFunction("hello", hello)
    server.Start()
    ...

To create a hprose Unix client is the same as TCP client:

    ...
    client := hprose.NewClient("unix:/tmp/my.sock")
    ...
WebSocket Server and Client

Hprose for Golang supports WebSocket Socket Server and Client. It is very easy to use like the HTTP Server and Client.

To create a hprose WebSocket service, you can use NewWebSocketService. For example:

    ...
	service := hprose.NewWebSocketService()
    service.AddFunction("hello", hello, true)
    http.ListenAndServe(":8080", service)
    ...

Hprose WebSocket service is also HTTP service. Not only hprose WebSocket client can invoke it, but also hprose HTTP client.

To create a hprose WebSocket client is the same as HTTP client:

    ...
    client := hprose.NewClient("ws://127.0.0.1:8080/")
    ...
Service Event

Hprose defines a ServiceEvent interface.

type ServiceEvent interface {
    OnBeforeInvoke(name string, args []reflect.Value, byref bool, context hprose.Context)
    OnAfterInvoke(name string, args []reflect.Value, byref bool, result []reflect.Value, context hprose.Context)
    OnSendError(err error, context hprose.Context)
}

If you want to log some thing about the service, you can implement this interface. For example:

package main

import (
    "fmt"
    "github.com/hprose/hprose-go"
    "net/http"
    "reflect"
)

func hello(name string) string {
    return "Hello " + name + "!"
}

type myServiceEvent struct{}

func (myServiceEvent) OnBeforeInvoke(name string, args []reflect.Value, byref bool, context hprose.Context) {
    fmt.Println(name, args, byref)
}

func (myServiceEvent) OnAfterInvoke(name string, args []reflect.Value, byref bool, result []reflect.Value, context hprose.Context) {
    fmt.Println(name, args, byref, result)
}

func (myServiceEvent) OnSendError(err error, context hprose.Context) {
    fmt.Println(err)
}

func main() {
    service := hprose.NewHttpService()
    service.ServiceEvent = myServiceEvent{}
    service.AddFunction("hello", hello)
    http.ListenAndServe(":8080", service)
}

The TcpService and TcpServer also have this interface field.

For hprose HTTP Service, you can implement HttpServiceEvent instead of ServiceEvent interface:

type HttpServiceEvent interface {
    ServiceEvent
    OnSendHeader(context *hprose.HttpContext)
}

Benchmark

Hprose is faster than golang RPC, you can run benchmark like this:

go test --bench=".*" github.com/hprose/hprose-go/bench

Here is the result with Go 1.4 on an Intel i7-2600:

benchmark iter time/iter
BenchmarkHprose 20000 63018 ns/op
BenchmarkHprose2 20000 66637 ns/op
BenchmarkGobRPC 20000 92289 ns/op
BenchmarkJSONRPC 10000 103602 ns/op

Documentation

Overview

Package hprose client example:

package main

import (
	"fmt"
	"hprose"
)

type testUser struct {
	Name     string
	Sex      int
	Birthday time.Time
	Age      int
	Married  bool
}

type testRemoteObject struct {
	Hello               func(string) string
	HelloWithError      func(string) (string, error)               `name:"hello"`
	AsyncHello          func(string) <-chan string                 `name:"hello"`
	AsyncHelloWithError func(string) (<-chan string, <-chan error) `name:"hello"`
	Sum                 func(...int) int
	SwapKeyAndValue     func(*map[string]string) map[string]string `byref:"true"`
	SwapInt             func(int, int) (int, int)                  `name:"swap"`
	SwapFloat           func(float64, float64) (float64, float64)  `name:"swap"`
	Swap                func(interface{}, interface{}) (interface{}, interface{})
	GetUserList         func() []testUser
}

func main() {
	client := hprose.NewClient("http://www.hprose.com/example/")
	var ro *RemoteObject
	client.UseService(&ro)

	// If an error occurs, it will panic
	fmt.Println(ro.Hello("World"))

	// If an error occurs, an error value will be returned
	if result, err := ro.HelloWithError("World"); err == nil {
		fmt.Println(result)
	} else {
		fmt.Println(err.Error())
	}

	// If an error occurs, it will be ignored
	result := ro.AsyncHello("World")
	fmt.Println(<-result)

	// If an error occurs, an error chan will be returned
	result, err := ro.AsyncHelloWithError("World")
	if e := <-err; e == nil {
		fmt.Println(<-result)
	} else {
		fmt.Println(e.Error())
	}
	fmt.Println(ro.Sum(1, 2, 3, 4, 5))

	m := make(map[string]string)
	m["Jan"] = "January"
	m["Feb"] = "February"
	m["Mar"] = "March"
	m["Apr"] = "April"
	m["May"] = "May"
	m["Jun"] = "June"
	m["Jul"] = "July"
	m["Aug"] = "August"
	m["Sep"] = "September"
	m["Oct"] = "October"
	m["Nov"] = "November"
	m["Dec"] = "December"

	fmt.Println(m)
	mm := ro.SwapKeyAndValue(&m)
	fmt.Println(m)
	fmt.Println(mm)

	fmt.Println(ro.GetUserList())
	fmt.Println(ro.SwapInt(1, 2))
	fmt.Println(ro.SwapFloat(1.2, 3.4))
	fmt.Println(ro.Swap("Hello", "World"))
}

Package hprose is a High Performance Remote Object Service Engine.

It is a modern, lightweight, cross-language, cross-platform, object-oriented, high performance, remote dynamic communication middleware. It is not only easy to use, but powerful. You just need a little time to learn, then you can use it to easily construct cross language cross platform distributed application system.

Hprose supports many programming languages, for example:

  • AAuto Quicker
  • ActionScript
  • ASP
  • C++
  • Dart
  • Delphi/Free Pascal
  • dotNET(C#, Visual Basic...)
  • Golang
  • Java
  • JavaScript
  • Node.js
  • Objective-C
  • Perl
  • PHP
  • Python
  • Ruby
  • ...

Through Hprose, You can conveniently and efficiently intercommunicate between those programming languages.

This project is the implementation of Hprose for Golang.

Index

Constants

View Source
const (
	// Normal is default mode
	Normal = ResultMode(iota)
	// Serialized means the result is serialized
	Serialized
	// Raw means the result is the raw bytes data
	Raw
	// RawWithEndTag means the result is the raw bytes data with the end tag
	RawWithEndTag
)
View Source
const (
	/* Serialize Tags */
	TagInteger  byte = 'i'
	TagLong     byte = 'l'
	TagDouble   byte = 'd'
	TagNull     byte = 'n'
	TagEmpty    byte = 'e'
	TagTrue     byte = 't'
	TagFalse    byte = 'f'
	TagNaN      byte = 'N'
	TagInfinity byte = 'I'
	TagDate     byte = 'D'
	TagTime     byte = 'T'
	TagUTC      byte = 'Z'
	TagBytes    byte = 'b'
	TagUTF8Char byte = 'u'
	TagString   byte = 's'
	TagGuid     byte = 'g'
	TagList     byte = 'a'
	TagMap      byte = 'm'
	TagClass    byte = 'c'
	TagObject   byte = 'o'
	TagRef      byte = 'r'
	/* Serialize Marks */
	TagPos        byte = '+'
	TagNeg        byte = '-'
	TagSemicolon  byte = ';'
	TagOpenbrace  byte = '{'
	TagClosebrace byte = '}'
	TagQuote      byte = '"'
	TagPoint      byte = '.'
	/* Protocol Tags */
	TagFunctions byte = 'F'
	TagCall      byte = 'C'
	TagResult    byte = 'R'
	TagArgument  byte = 'A'
	TagError     byte = 'E'
	TagEnd       byte = 'z'
)

Variables

View Source
var ClassManager = initClassManager()

ClassManager used to be register class with alias for hprose serialize/unserialize.

View Source
var DisableGlobalCookie = false

DisableGlobalCookie is a flag to disable global cookie

View Source
var ErrNil = errors.New("nil")

ErrNil is a error of nil

Functions

func Marshal

func Marshal(v interface{}) ([]byte, error)

Marshal data

func RegisterClientFactory

func RegisterClientFactory(scheme string, newClient func(string) Client)

RegisterClientFactory register client factory

func Serialize

func Serialize(v interface{}, simple bool) ([]byte, error)

Serialize data

func Unmarshal

func Unmarshal(b []byte, p interface{}) error

Unmarshal data

func Unserialize

func Unserialize(b []byte, p interface{}, simple bool) error

Unserialize data

Types

type ArgsFixer

type ArgsFixer interface {
	FixArgs(args []reflect.Value, lastParamType reflect.Type, context Context) []reflect.Value
}

ArgsFixer ...

type BaseClient

type BaseClient struct {
	Transporter
	Client
	ByRef        bool
	SimpleMode   bool
	DebugEnabled bool
	// contains filtered or unexported fields
}

BaseClient is the hprose base client

func NewBaseClient

func NewBaseClient(trans Transporter) *BaseClient

NewBaseClient is the constructor of BaseClient

func (*BaseClient) AddFilter

func (client *BaseClient) AddFilter(filter Filter)

AddFilter add a filter

func (*BaseClient) GetFilter

func (client *BaseClient) GetFilter() Filter

GetFilter return the first filter

func (*BaseClient) Invoke

func (client *BaseClient) Invoke(name string, args []interface{}, options *InvokeOptions, result interface{}) <-chan error

Invoke the remote method

func (*BaseClient) RemoveFilter

func (client *BaseClient) RemoveFilter(filter Filter)

RemoveFilter remove a filter

func (*BaseClient) SetFilter

func (client *BaseClient) SetFilter(filter Filter)

SetFilter set the only filter

func (*BaseClient) SetUri

func (client *BaseClient) SetUri(uri string)

SetUri set the uri of hprose client

func (*BaseClient) Uri

func (client *BaseClient) Uri() string

Uri return the uri of hprose client

func (*BaseClient) UseService

func (client *BaseClient) UseService(args ...interface{})

UseService (uri string) UseService (remoteObject interface{}) UseService (uri string, remoteObject interface{})

type BaseContext

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

BaseContext is the hprose base context

func NewBaseContext

func NewBaseContext() (context *BaseContext)

NewBaseContext is the constructor of BaseContext

func (*BaseContext) GetBool

func (context *BaseContext) GetBool(key string) (value bool, ok bool)

GetBool from hprose context

func (*BaseContext) GetFloat

func (context *BaseContext) GetFloat(key string) (value float64, ok bool)

GetFloat from hprose context

func (*BaseContext) GetInt

func (context *BaseContext) GetInt(key string) (value int, ok bool)

GetInt from hprose context

func (*BaseContext) GetInt64

func (context *BaseContext) GetInt64(key string) (value int64, ok bool)

GetInt64 from hprose context

func (*BaseContext) GetInterface

func (context *BaseContext) GetInterface(key string) (value interface{}, ok bool)

GetInterface from hprose context

func (*BaseContext) GetString

func (context *BaseContext) GetString(key string) (value string, ok bool)

GetString from hprose context

func (*BaseContext) GetUInt

func (context *BaseContext) GetUInt(key string) (value uint, ok bool)

GetUInt from hprose context

func (*BaseContext) GetUInt64

func (context *BaseContext) GetUInt64(key string) (value uint64, ok bool)

GetUInt64 from hprose context

func (*BaseContext) SetBool

func (context *BaseContext) SetBool(key string, value bool)

SetBool to hprose context

func (*BaseContext) SetFloat

func (context *BaseContext) SetFloat(key string, value float64)

SetFloat to hprose context

func (*BaseContext) SetInt

func (context *BaseContext) SetInt(key string, value int)

SetInt to hprose context

func (*BaseContext) SetInt64

func (context *BaseContext) SetInt64(key string, value int64)

SetInt64 to hprose context

func (*BaseContext) SetInterface

func (context *BaseContext) SetInterface(key string, value interface{})

SetInterface to hprose context

func (*BaseContext) SetString

func (context *BaseContext) SetString(key string, value string)

SetString to hprose context

func (*BaseContext) SetUInt

func (context *BaseContext) SetUInt(key string, value uint)

SetUInt to hprose context

func (*BaseContext) SetUInt64

func (context *BaseContext) SetUInt64(key string, value uint64)

SetUInt64 to hprose context

func (*BaseContext) UserData

func (context *BaseContext) UserData() map[string]interface{}

UserData return the user data

type BaseService

type BaseService struct {
	*Methods
	ServiceEvent
	DebugEnabled bool
	// contains filtered or unexported fields
}

BaseService is the hprose base service

func NewBaseService

func NewBaseService() (service *BaseService)

NewBaseService is the constructor for BaseService

func (*BaseService) AddFilter

func (service *BaseService) AddFilter(filter Filter)

AddFilter add a filter

func (*BaseService) GetFilter

func (service *BaseService) GetFilter() Filter

GetFilter return the first filter

func (*BaseService) Handle

func (service *BaseService) Handle(data []byte, context Context) (output []byte)

Handle the hprose request and return the hprose response

func (*BaseService) RemoveFilter

func (service *BaseService) RemoveFilter(filter Filter)

RemoveFilter remove a filter

func (*BaseService) SetFilter

func (service *BaseService) SetFilter(filter Filter)

SetFilter set the only filter

type BufReader

type BufReader interface {
	Read(p []byte) (n int, err error)
	ReadByte() (c byte, err error)
	ReadRune() (r rune, size int, err error)
	ReadString(delim byte) (line string, err error)
}

BufReader is buffer reader interface, Hprose Reader use it as input stream.

type BufWriter

type BufWriter interface {
	Write(p []byte) (n int, err error)
	WriteByte(c byte) error
	WriteRune(r rune) (n int, err error)
	WriteString(s string) (n int, err error)
}

BufWriter is buffer writer interface, Hprose Writer use it as output stream.

type BytesReader

type BytesReader struct {
	Bytes []byte
	Pos   int
}

BytesReader is a bytes reader

func NewBytesReader

func NewBytesReader(b []byte) (reader *BytesReader)

NewBytesReader is the constructor of BytesReader

func (*BytesReader) Read

func (r *BytesReader) Read(b []byte) (n int, err error)

Read bytes from BytesReader

func (*BytesReader) ReadByte

func (r *BytesReader) ReadByte() (b byte, err error)

ReadByte from BytesReader

func (*BytesReader) ReadRune

func (r *BytesReader) ReadRune() (ch rune, size int, err error)

ReadRune from BytesReader

func (*BytesReader) ReadString

func (r *BytesReader) ReadString(delim byte) (line string, err error)

ReadString from BytesReader

type Client

type Client interface {
	UseService(...interface{})
	Invoke(string, []interface{}, *InvokeOptions, interface{}) <-chan error
	Uri() string
	SetUri(string)
	GetFilter() Filter
	SetFilter(filter Filter)
	AddFilter(filter Filter)
	RemoveFilter(filter Filter)
	TLSClientConfig() *tls.Config
	SetTLSClientConfig(config *tls.Config)
	SetKeepAlive(enable bool)
	Close()
}

Client is hprose client

func NewClient

func NewClient(uri string) Client

NewClient is the constructor of Client

type ClientContext

type ClientContext struct {
	*BaseContext
	Client
}

ClientContext is the hprose client context

type ConnEntry

type ConnEntry interface {
	Get() net.Conn
	Set(conn net.Conn)
	Close()
}

ConnEntry is the connection entry in connection pool

func NewStreamConnEntry

func NewStreamConnEntry(uri string) ConnEntry

NewStreamConnEntry is the constructor for StreamConnEntry

type ConnPool

type ConnPool interface {
	Timeout() time.Duration
	SetTimeout(d time.Duration)
	Get(uri string) ConnEntry
	Close(uri string)
	Free(entry ConnEntry)
}

ConnPool is the connection pool

func NewStreamConnPool

func NewStreamConnPool(num int) ConnPool

NewStreamConnPool is the constructor for StreamConnPool

type Context

type Context interface {
	UserData() map[string]interface{}
	GetInt(key string) (value int, ok bool)
	GetUInt(key string) (value uint, ok bool)
	GetInt64(key string) (value int64, ok bool)
	GetUInt64(key string) (value uint64, ok bool)
	GetFloat(key string) (value float64, ok bool)
	GetBool(key string) (value bool, ok bool)
	GetString(key string) (value string, ok bool)
	GetInterface(key string) (value interface{}, ok bool)
	SetInt(key string, value int)
	SetUInt(key string, value uint)
	SetInt64(key string, value int64)
	SetUInt64(key string, value uint64)
	SetFloat(key string, value float64)
	SetBool(key string, value bool)
	SetString(key string, value string)
	SetInterface(key string, value interface{})
}

Context is the hprose context

type Filter

type Filter interface {
	InputFilter(data []byte, context Context) []byte
	OutputFilter(data []byte, context Context) []byte
}

Filter is hprose filter

type HttpClient

type HttpClient struct {
	*BaseClient
}

HttpClient is hprose http client

func NewHttpClient

func NewHttpClient(uri string) (client *HttpClient)

NewHttpClient is the constructor of HttpClient

func (*HttpClient) Close

func (client *HttpClient) Close()

Close the client

func (*HttpClient) Compression

func (client *HttpClient) Compression() bool

Compression return the compression status of hprose client

func (*HttpClient) Header

func (client *HttpClient) Header() *http.Header

Header return the http.Header in hprose client

func (*HttpClient) Http

func (client *HttpClient) Http() *http.Client

Http return the http.Client in hprose client

func (*HttpClient) KeepAlive

func (client *HttpClient) KeepAlive() bool

KeepAlive return the keepalive status of hprose client

func (*HttpClient) MaxIdleConnsPerHost

func (client *HttpClient) MaxIdleConnsPerHost() int

MaxIdleConnsPerHost return the max idle connections per host of hprose client

func (*HttpClient) SetCompression

func (client *HttpClient) SetCompression(enable bool)

SetCompression set the compression status of hprose client

func (*HttpClient) SetKeepAlive

func (client *HttpClient) SetKeepAlive(enable bool)

SetKeepAlive set the keepalive status of hprose client

func (*HttpClient) SetMaxIdleConnsPerHost

func (client *HttpClient) SetMaxIdleConnsPerHost(value int)

SetMaxIdleConnsPerHost set the max idle connections per host of hprose client

func (*HttpClient) SetTLSClientConfig

func (client *HttpClient) SetTLSClientConfig(config *tls.Config)

SetTLSClientConfig set the tls.Config

func (*HttpClient) SetUri

func (client *HttpClient) SetUri(uri string)

SetUri set the uri of hprose client

func (*HttpClient) TLSClientConfig

func (client *HttpClient) TLSClientConfig() *tls.Config

TLSClientConfig return the tls.Config in hprose client

type HttpContext

type HttpContext struct {
	*BaseContext
	Response http.ResponseWriter
	Request  *http.Request
}

HttpContext is the hprose http context

type HttpService

type HttpService struct {
	*BaseService
	P3PEnabled         bool
	GetEnabled         bool
	CrossDomainEnabled bool
	// contains filtered or unexported fields
}

HttpService is the hprose http service

func NewHttpService

func NewHttpService() (service *HttpService)

NewHttpService is the constructor of HttpService

func (*HttpService) AddAccessControlAllowOrigin

func (service *HttpService) AddAccessControlAllowOrigin(origin string)

AddAccessControlAllowOrigin add access control allow origin

func (*HttpService) ClientAccessPolicyXmlContent

func (service *HttpService) ClientAccessPolicyXmlContent() []byte

ClientAccessPolicyXmlContent return the client access policy xml content

func (*HttpService) ClientAccessPolicyXmlFile

func (service *HttpService) ClientAccessPolicyXmlFile() string

ClientAccessPolicyXmlFile return the client access policy xml file

func (*HttpService) CrossDomainXmlContent

func (service *HttpService) CrossDomainXmlContent() []byte

CrossDomainXmlContent return the cross domain xml content

func (*HttpService) CrossDomainXmlFile

func (service *HttpService) CrossDomainXmlFile() string

CrossDomainXmlFile return the cross domain xml file

func (*HttpService) RemoveAccessControlAllowOrigin

func (service *HttpService) RemoveAccessControlAllowOrigin(origin string)

RemoveAccessControlAllowOrigin remove access control allow origin

func (*HttpService) Serve

func (service *HttpService) Serve(response http.ResponseWriter, request *http.Request, userData map[string]interface{})

Serve ...

func (*HttpService) ServeHTTP

func (service *HttpService) ServeHTTP(response http.ResponseWriter, request *http.Request)

ServeHTTP ...

func (*HttpService) SetClientAccessPolicyXmlContent

func (service *HttpService) SetClientAccessPolicyXmlContent(content []byte)

SetClientAccessPolicyXmlContent set the client access policy xml content

func (*HttpService) SetClientAccessPolicyXmlFile

func (service *HttpService) SetClientAccessPolicyXmlFile(filename string)

SetClientAccessPolicyXmlFile set the client access policy xml file

func (*HttpService) SetCrossDomainXmlContent

func (service *HttpService) SetCrossDomainXmlContent(content []byte)

SetCrossDomainXmlContent set the cross domain xml content

func (*HttpService) SetCrossDomainXmlFile

func (service *HttpService) SetCrossDomainXmlFile(filename string)

SetCrossDomainXmlFile set the cross domain xml file

type HttpServiceEvent

type HttpServiceEvent interface {
	ServiceEvent
	OnSendHeader(context *HttpContext)
}

HttpServiceEvent is the hprose http service event

type InvokeOptions

type InvokeOptions struct {
	ByRef      interface{} // true, false, nil
	SimpleMode interface{} // true, false, nil
	ResultMode ResultMode
}

InvokeOptions is the invoke options of hprose client

type JSONRPCClientFilter

type JSONRPCClientFilter struct {
	Version string
}

JSONRPCClientFilter is a JSONRPC Client Filter

func NewJSONRPCClientFilter

func NewJSONRPCClientFilter(version string) JSONRPCClientFilter

NewJSONRPCClientFilter is a constructor for JSONRPCClientFilter

func (JSONRPCClientFilter) InputFilter

func (filter JSONRPCClientFilter) InputFilter(data []byte, context Context) []byte

InputFilter for JSONRPC Client

func (JSONRPCClientFilter) OutputFilter

func (filter JSONRPCClientFilter) OutputFilter(data []byte, context Context) []byte

OutputFilter for JSONRPC Client

type JSONRPCServiceFilter

type JSONRPCServiceFilter struct{}

JSONRPCServiceFilter is a JSONRPC Service Filter

func (JSONRPCServiceFilter) InputFilter

func (filter JSONRPCServiceFilter) InputFilter(data []byte, context Context) []byte

InputFilter for JSONRPC Service

func (JSONRPCServiceFilter) OutputFilter

func (filter JSONRPCServiceFilter) OutputFilter(data []byte, context Context) []byte

OutputFilter for JSONRPC Service

type Method

type Method struct {
	Function   reflect.Value
	ResultMode ResultMode
	SimpleMode bool
}

Method is the publish service method

func NewMethod

func NewMethod(f reflect.Value, mode ResultMode, simple bool) (method *Method)

NewMethod is the constructor for Method

type Methods

type Methods struct {
	MethodNames   []string
	RemoteMethods map[string]*Method
}

Methods is the publish service methods

func NewMethods

func NewMethods() (methods *Methods)

NewMethods is the constructor for Methods

func (*Methods) AddAllMethods

func (methods *Methods) AddAllMethods(obj interface{}, options ...interface{})

AddAllMethods will publish all methods and non-nil function fields on the obj self and on its anonymous or non-anonymous struct fields (or pointer to pointer ... to pointer struct fields). This is a recursive operation. So it's a pit, if you do not know what you are doing, do not step on.

func (*Methods) AddFunction

func (methods *Methods) AddFunction(name string, function interface{}, options ...interface{})

AddFunction publish a func or bound method name is the method name function is a func or bound method options is ResultMode, SimpleMode and prefix

func (*Methods) AddFunctions

func (methods *Methods) AddFunctions(names []string, functions []interface{}, options ...interface{})

AddFunctions ... names are method names functions are funcs or bound methods options is the same as AddFuntion

func (*Methods) AddMethods

func (methods *Methods) AddMethods(obj interface{}, options ...interface{})

AddMethods ... obj is service object. all the public method and func field will be published options is the same as AddFuntion

func (*Methods) AddMissingMethod

func (methods *Methods) AddMissingMethod(method MissingMethod, options ...interface{})

AddMissingMethod ... All methods not explicitly published will be redirected to the method.

type MissingMethod

type MissingMethod func(name string, args []reflect.Value) (result []reflect.Value)

MissingMethod is missing method

type RawReader

type RawReader struct {
	Stream BufReader
}

RawReader is the hprose raw reader

func NewRawReader

func NewRawReader(stream BufReader) (reader *RawReader)

NewRawReader is a constructor for RawReader

func (*RawReader) ReadRaw

func (r *RawReader) ReadRaw() (raw []byte, err error)

ReadRaw from stream

func (*RawReader) ReadRawTo

func (r *RawReader) ReadRawTo(ostream BufWriter) (err error)

ReadRawTo ostream from stream

type Reader

type Reader struct {
	*RawReader

	JSONCompatible bool
	// contains filtered or unexported fields
}

Reader is a fine-grained operation struct for Hprose unserialization when JSONCompatible is true, the Map data will unserialize to map[string]interface as the default type

func NewReader

func NewReader(stream BufReader, simple bool) (reader *Reader)

NewReader is the constructor for Hprose Reader

func (*Reader) CheckTag

func (r *Reader) CheckTag(expectTag byte) error

CheckTag the next byte in stream is the expected tag

func (*Reader) CheckTags

func (r *Reader) CheckTags(expectTags []byte) (tag byte, err error)

CheckTags the next byte in stream in the expected tags

func (*Reader) ReadArray

func (r *Reader) ReadArray(a []reflect.Value) error

ReadArray from stream

func (*Reader) ReadBigInt

func (r *Reader) ReadBigInt() (*big.Int, error)

ReadBigInt from stream

func (*Reader) ReadBigIntWithoutTag

func (r *Reader) ReadBigIntWithoutTag() (*big.Int, error)

ReadBigIntWithoutTag from stream

func (*Reader) ReadBool

func (r *Reader) ReadBool() (bool, error)

ReadBool from stream

func (*Reader) ReadBytes

func (r *Reader) ReadBytes() (*[]byte, error)

ReadBytes from stream

func (*Reader) ReadBytesWithoutTag

func (r *Reader) ReadBytesWithoutTag() (*[]byte, error)

ReadBytesWithoutTag from stream

func (*Reader) ReadDateTime

func (r *Reader) ReadDateTime() (time.Time, error)

ReadDateTime from stream

func (*Reader) ReadDateWithoutTag

func (r *Reader) ReadDateWithoutTag() (time.Time, error)

ReadDateWithoutTag from stream

func (*Reader) ReadFloat32

func (r *Reader) ReadFloat32() (float32, error)

ReadFloat32 from stream

func (*Reader) ReadFloat32WithoutTag

func (r *Reader) ReadFloat32WithoutTag() (float32, error)

ReadFloat32WithoutTag from stream

func (*Reader) ReadFloat64

func (r *Reader) ReadFloat64() (float64, error)

ReadFloat64 from stream

func (*Reader) ReadFloat64WithoutTag

func (r *Reader) ReadFloat64WithoutTag() (float64, error)

ReadFloat64WithoutTag from stream

func (*Reader) ReadInt

func (r *Reader) ReadInt() (int, error)

ReadInt from stream

func (*Reader) ReadInt16

func (r *Reader) ReadInt16() (int16, error)

ReadInt16 from stream

func (*Reader) ReadInt16WithoutTag

func (r *Reader) ReadInt16WithoutTag() (int16, error)

ReadInt16WithoutTag from stream

func (*Reader) ReadInt32

func (r *Reader) ReadInt32() (int32, error)

ReadInt32 from stream

func (*Reader) ReadInt32WithoutTag

func (r *Reader) ReadInt32WithoutTag() (int32, error)

ReadInt32WithoutTag from stream

func (*Reader) ReadInt64

func (r *Reader) ReadInt64() (int64, error)

ReadInt64 from stream

func (*Reader) ReadInt64WithoutTag

func (r *Reader) ReadInt64WithoutTag() (int64, error)

ReadInt64WithoutTag from stream

func (*Reader) ReadInt8

func (r *Reader) ReadInt8() (int8, error)

ReadInt8 from stream

func (*Reader) ReadInt8WithoutTag

func (r *Reader) ReadInt8WithoutTag() (int8, error)

ReadInt8WithoutTag from stream

func (*Reader) ReadIntWithoutTag

func (r *Reader) ReadIntWithoutTag() (int, error)

ReadIntWithoutTag from stream

func (*Reader) ReadInteger

func (r *Reader) ReadInteger(tag byte) (int, error)

ReadInteger from stream

func (*Reader) ReadList

func (r *Reader) ReadList() (*list.List, error)

ReadList from stream

func (*Reader) ReadListWithoutTag

func (r *Reader) ReadListWithoutTag() (*list.List, error)

ReadListWithoutTag from stream

func (*Reader) ReadMap

func (r *Reader) ReadMap(p interface{}) error

ReadMap from stream

func (*Reader) ReadMapWithoutTag

func (r *Reader) ReadMapWithoutTag(p interface{}) error

ReadMapWithoutTag from stream

func (*Reader) ReadObject

func (r *Reader) ReadObject(p interface{}) error

ReadObject from stream

func (*Reader) ReadObjectWithoutTag

func (r *Reader) ReadObjectWithoutTag(p interface{}) error

ReadObjectWithoutTag from stream

func (*Reader) ReadSlice

func (r *Reader) ReadSlice(p interface{}) error

ReadSlice from stream

func (*Reader) ReadSliceWithoutTag

func (r *Reader) ReadSliceWithoutTag(p interface{}) error

ReadSliceWithoutTag from stream

func (*Reader) ReadString

func (r *Reader) ReadString() (string, error)

ReadString from stream

func (*Reader) ReadStringWithoutTag

func (r *Reader) ReadStringWithoutTag() (str string, err error)

ReadStringWithoutTag from stream

func (*Reader) ReadTimeWithoutTag

func (r *Reader) ReadTimeWithoutTag() (time.Time, error)

ReadTimeWithoutTag from stream

func (*Reader) ReadUUID

func (r *Reader) ReadUUID() (*UUID, error)

ReadUUID from stream

func (*Reader) ReadUUIDWithoutTag

func (r *Reader) ReadUUIDWithoutTag() (*UUID, error)

ReadUUIDWithoutTag from stream

func (*Reader) ReadUint

func (r *Reader) ReadUint() (uint, error)

ReadUint from stream

func (*Reader) ReadUint16

func (r *Reader) ReadUint16() (uint16, error)

ReadUint16 from stream

func (*Reader) ReadUint16WithoutTag

func (r *Reader) ReadUint16WithoutTag() (uint16, error)

ReadUint16WithoutTag from stream

func (*Reader) ReadUint32

func (r *Reader) ReadUint32() (uint32, error)

ReadUint32 from stream

func (*Reader) ReadUint32WithoutTag

func (r *Reader) ReadUint32WithoutTag() (uint32, error)

ReadUint32WithoutTag from stream

func (*Reader) ReadUint64

func (r *Reader) ReadUint64() (uint64, error)

ReadUint64 from stream

func (*Reader) ReadUint64WithoutTag

func (r *Reader) ReadUint64WithoutTag() (uint64, error)

ReadUint64WithoutTag from stream

func (*Reader) ReadUint8

func (r *Reader) ReadUint8() (uint8, error)

ReadUint8 from stream

func (*Reader) ReadUint8WithoutTag

func (r *Reader) ReadUint8WithoutTag() (uint8, error)

ReadUint8WithoutTag from stream

func (*Reader) ReadUintWithoutTag

func (r *Reader) ReadUintWithoutTag() (uint, error)

ReadUintWithoutTag from stream

func (*Reader) ReadUinteger

func (r *Reader) ReadUinteger(tag byte) (uint, error)

ReadUinteger from stream

func (*Reader) ReadValue

func (r *Reader) ReadValue(v reflect.Value) error

ReadValue from stream

func (*Reader) Reset

func (r *Reader) Reset()

Reset the serialize reference count

func (*Reader) Unserialize

func (r *Reader) Unserialize(p interface{}) (err error)

Unserialize a data from stream

type ResultMode

type ResultMode int

ResultMode is result mode

func (ResultMode) String

func (result_mode ResultMode) String() string

type ServiceEvent

type ServiceEvent interface {
	OnBeforeInvoke(name string, args []reflect.Value, byref bool, context Context)
	OnAfterInvoke(name string, args []reflect.Value, byref bool, result []reflect.Value, context Context)
	OnSendError(err error, context Context)
}

ServiceEvent is the service event

type StreamClient

type StreamClient struct {
	*BaseClient
	// contains filtered or unexported fields
}

StreamClient is base struct for TcpClient and UnixClient

func (*StreamClient) SetReadBuffer

func (client *StreamClient) SetReadBuffer(bytes int)

SetReadBuffer sets the size of the operating system's receive buffer associated with the connection.

func (*StreamClient) SetReadTimeout

func (client *StreamClient) SetReadTimeout(d time.Duration)

SetReadTimeout for stream client

func (*StreamClient) SetWriteBuffer

func (client *StreamClient) SetWriteBuffer(bytes int)

SetWriteBuffer sets the size of the operating system's transmit buffer associated with the connection.

func (*StreamClient) SetWriteTimeout

func (client *StreamClient) SetWriteTimeout(d time.Duration)

SetWriteTimeout for stream client

type StreamContext

type StreamContext struct {
	*BaseContext
	net.Conn
}

StreamContext is the hprose stream context for service

type StreamService

type StreamService struct {
	*BaseService
	// contains filtered or unexported fields
}

StreamService is the base service for TcpService and UnixService

func (*StreamService) SetReadBuffer

func (service *StreamService) SetReadBuffer(bytes int)

SetReadBuffer for stream service

func (*StreamService) SetReadTimeout

func (service *StreamService) SetReadTimeout(d time.Duration)

SetReadTimeout for stream service

func (*StreamService) SetTimeout

func (service *StreamService) SetTimeout(d time.Duration)

SetTimeout for stream service

func (*StreamService) SetWriteBuffer

func (service *StreamService) SetWriteBuffer(bytes int)

SetWriteBuffer for stream service

func (*StreamService) SetWriteTimeout

func (service *StreamService) SetWriteTimeout(d time.Duration)

SetWriteTimeout for stream service

type TcpClient

type TcpClient struct {
	*StreamClient
	// contains filtered or unexported fields
}

TcpClient is hprose tcp client

func NewTcpClient

func NewTcpClient(uri string) (client *TcpClient)

NewTcpClient is the constructor of TcpClient

func (*TcpClient) Close

func (client *TcpClient) Close()

Close the client

func (*TcpClient) SetConnPool

func (client *TcpClient) SetConnPool(connPool ConnPool)

SetConnPool can set separate StreamConnPool for the client

func (*TcpClient) SetKeepAlive

func (client *TcpClient) SetKeepAlive(keepalive bool)

SetKeepAlive sets whether the operating system should send keepalive messages on the connection.

func (*TcpClient) SetKeepAlivePeriod

func (client *TcpClient) SetKeepAlivePeriod(d time.Duration)

SetKeepAlivePeriod sets period between keep alives.

func (*TcpClient) SetLinger

func (client *TcpClient) SetLinger(sec int)

SetLinger sets the behavior of Close on a connection which still has data waiting to be sent or to be acknowledged.

If sec < 0 (the default), the operating system finishes sending the data in the background.

If sec == 0, the operating system discards any unsent or unacknowledged data.

If sec > 0, the data is sent in the background as with sec < 0. On some operating systems after sec seconds have elapsed any remaining unsent data may be discarded.

func (*TcpClient) SetNoDelay

func (client *TcpClient) SetNoDelay(noDelay bool)

SetNoDelay controls whether the operating system should delay packet transmission in hopes of sending fewer packets (Nagle's algorithm). The default is true (no delay), meaning that data is sent as soon as possible after a Write.

func (*TcpClient) SetTLSClientConfig

func (client *TcpClient) SetTLSClientConfig(config *tls.Config)

SetTLSClientConfig sets the Config structure used to configure a TLS client

func (*TcpClient) SetTimeout

func (client *TcpClient) SetTimeout(d time.Duration)

SetTimeout for connection in client pool

func (*TcpClient) SetUri

func (client *TcpClient) SetUri(uri string)

SetUri set the uri of hprose client

func (*TcpClient) TLSClientConfig

func (client *TcpClient) TLSClientConfig() *tls.Config

TLSClientConfig returns the Config structure used to configure a TLS client

func (*TcpClient) Timeout

func (client *TcpClient) Timeout() time.Duration

Timeout return the timeout of the connection in client pool

type TcpContext

type TcpContext StreamContext

TcpContext is the hprose tcp context

type TcpServer

type TcpServer struct {
	*TcpService
	URL string
	// contains filtered or unexported fields
}

TcpServer is a hprose tcp server

func NewTcpServer

func NewTcpServer(uri string) (server *TcpServer)

NewTcpServer is a constructor for TcpServer

func (*TcpServer) Handle

func (server *TcpServer) Handle() (err error)

Handle the hprose tcp server

func (*TcpServer) Start

func (server *TcpServer) Start() (err error)

Start the hprose tcp server

func (*TcpServer) Stop

func (server *TcpServer) Stop()

Stop the hprose tcp server

type TcpService

type TcpService struct {
	*StreamService
	// contains filtered or unexported fields
}

TcpService is the hprose tcp service

func NewTcpService

func NewTcpService() (service *TcpService)

NewTcpService is the constructor of TcpService

func (*TcpService) ServeTCP

func (service *TcpService) ServeTCP(conn *net.TCPConn) (err error)

ServeTCP ...

func (*TcpService) SetKeepAlive

func (service *TcpService) SetKeepAlive(keepalive bool)

SetKeepAlive sets whether the operating system should send keepalive messages on the connection.

func (*TcpService) SetKeepAlivePeriod

func (service *TcpService) SetKeepAlivePeriod(d time.Duration)

SetKeepAlivePeriod sets period between keep alives.

func (*TcpService) SetLinger

func (service *TcpService) SetLinger(sec int)

SetLinger sets the behavior of Close on a connection which still has data waiting to be sent or to be acknowledged.

If sec < 0 (the default), the operating system finishes sending the data in the background.

If sec == 0, the operating system discards any unsent or unacknowledged data.

If sec > 0, the data is sent in the background as with sec < 0. On some operating systems after sec seconds have elapsed any remaining unsent data may be discarded.

func (*TcpService) SetNoDelay

func (service *TcpService) SetNoDelay(noDelay bool)

SetNoDelay controls whether the operating system should delay packet transmission in hopes of sending fewer packets (Nagle's algorithm). The default is true (no delay), meaning that data is sent as soon as possible after a Write.

func (*TcpService) SetTLSConfig

func (service *TcpService) SetTLSConfig(config *tls.Config)

SetTLSConfig sets the Config structure used to configure TLS service

type Transporter

type Transporter interface {
	SendAndReceive(uri string, data []byte) ([]byte, error)
}

Transporter is the hprose client transporter

type UUID

type UUID []byte

UUID type is only a UUID wrapper for hprose serialize/unserialize, If you want to generate UUIDs, you should use other UUID package.

func ToUUID

func ToUUID(s string) UUID

ToUUID decodes s into a UUID or returns nil. Both the UUID form of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded.

func (UUID) String

func (uuid UUID) String() string

String returns the string form of uuid, xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx , or "" if uuid is invalid.

type UnixClient

type UnixClient struct {
	*StreamClient
	// contains filtered or unexported fields
}

UnixClient is hprose unix client

func NewUnixClient

func NewUnixClient(uri string) (client *UnixClient)

NewUnixClient is the constructor of UnixClient

func (*UnixClient) Close

func (client *UnixClient) Close()

Close the client

func (*UnixClient) SetConnPool

func (client *UnixClient) SetConnPool(connPool ConnPool)

SetConnPool can set separate StreamConnPool for the client

func (*UnixClient) SetKeepAlive

func (client *UnixClient) SetKeepAlive(keepalive bool)

SetKeepAlive do nothing on unix client

func (*UnixClient) SetTLSClientConfig

func (client *UnixClient) SetTLSClientConfig(config *tls.Config)

SetTLSClientConfig sets the Config structure used to configure a TLS client

func (*UnixClient) SetTimeout

func (client *UnixClient) SetTimeout(d time.Duration)

SetTimeout for connection in client pool

func (*UnixClient) SetUri

func (client *UnixClient) SetUri(uri string)

SetUri set the uri of hprose client

func (*UnixClient) TLSClientConfig

func (client *UnixClient) TLSClientConfig() *tls.Config

TLSClientConfig returns the Config structure used to configure a TLS client

func (*UnixClient) Timeout

func (client *UnixClient) Timeout() time.Duration

Timeout return the timeout of the connection in client pool

type UnixContext

type UnixContext StreamContext

UnixContext is the hprose unix context

type UnixServer

type UnixServer struct {
	*UnixService
	URL string
	// contains filtered or unexported fields
}

UnixServer is a hprose unix server

func NewUnixServer

func NewUnixServer(uri string) (server *UnixServer)

NewUnixServer is a constructor for UnixServer

func (*UnixServer) Handle

func (server *UnixServer) Handle() (err error)

Handle the hprose unix server

func (*UnixServer) Start

func (server *UnixServer) Start() (err error)

Start the hprose unix server

func (*UnixServer) Stop

func (server *UnixServer) Stop()

Stop the hprose unix server

type UnixService

type UnixService StreamService

UnixService is the hprose unix service

func NewUnixService

func NewUnixService() *UnixService

NewUnixService is the constructor of UnixService

func (*UnixService) ServeUnix

func (service *UnixService) ServeUnix(conn *net.UnixConn) (err error)

ServeUnix ...

type WebSocketClient

type WebSocketClient struct {
	*BaseClient
}

WebSocketClient is hprose websocket client

func NewWebSocketClient

func NewWebSocketClient(uri string) (client *WebSocketClient)

NewWebSocketClient is the constructor of WebSocketClient

func (*WebSocketClient) Close

func (client *WebSocketClient) Close()

Close the client

func (*WebSocketClient) Header

func (client *WebSocketClient) Header() *http.Header

Header returns the http.Header in hprose client

func (*WebSocketClient) MaxConcurrentRequests

func (client *WebSocketClient) MaxConcurrentRequests() int

MaxConcurrentRequests returns the max concurrent requests of hprose client

func (*WebSocketClient) SetKeepAlive

func (client *WebSocketClient) SetKeepAlive(enable bool)

SetKeepAlive do nothing on WebSocketClient, it is always keepAlive

func (*WebSocketClient) SetMaxConcurrentRequests

func (client *WebSocketClient) SetMaxConcurrentRequests(value int)

SetMaxConcurrentRequests sets the max concurrent requests of hprose client

func (*WebSocketClient) SetTLSClientConfig

func (client *WebSocketClient) SetTLSClientConfig(config *tls.Config)

SetTLSClientConfig sets the tls.Config

func (*WebSocketClient) SetUri

func (client *WebSocketClient) SetUri(uri string)

SetUri set the uri of hprose client

func (*WebSocketClient) TLSClientConfig

func (client *WebSocketClient) TLSClientConfig() *tls.Config

TLSClientConfig returns the tls.Config in hprose client

type WebSocketContext

type WebSocketContext struct {
	*HttpContext
	WebSocket *websocket.Conn
}

WebSocketContext is the hprose websocket context

type WebSocketService

type WebSocketService struct {
	*HttpService
	*websocket.Upgrader
}

WebSocketService is the hprose websocket service

func NewWebSocketService

func NewWebSocketService() *WebSocketService

NewWebSocketService is the constructor of WebSocketService

func (*WebSocketService) ServeHTTP

func (service *WebSocketService) ServeHTTP(response http.ResponseWriter, request *http.Request)

ServeHTTP ...

type Writer

type Writer struct {
	Stream BufWriter
	// contains filtered or unexported fields
}

Writer is a fine-grained operation struct for Hprose serialization

func NewWriter

func NewWriter(stream BufWriter, simple bool) (writer *Writer)

NewWriter is the constructor for Hprose Writer

func (*Writer) Reset

func (w *Writer) Reset()

Reset the serialize reference count

func (*Writer) Serialize

func (w *Writer) Serialize(v interface{}) (err error)

Serialize a data to stream

func (*Writer) WriteArray

func (w *Writer) WriteArray(v []reflect.Value) (err error)

WriteArray to stream

func (*Writer) WriteBigInt

func (w *Writer) WriteBigInt(v *big.Int) (err error)

WriteBigInt to stream

func (*Writer) WriteBool

func (w *Writer) WriteBool(v bool) error

WriteBool to stream

func (*Writer) WriteBytes

func (w *Writer) WriteBytes(bytes []byte) (err error)

WriteBytes to stream

func (*Writer) WriteBytesWithRef

func (w *Writer) WriteBytesWithRef(bytes []byte) (err error)

WriteBytesWithRef to stream

func (*Writer) WriteFloat64

func (w *Writer) WriteFloat64(v float64) (err error)

WriteFloat64 to stream

func (*Writer) WriteInt64

func (w *Writer) WriteInt64(v int64) (err error)

WriteInt64 to stream

func (*Writer) WriteNull

func (w *Writer) WriteNull() error

WriteNull to stream

func (*Writer) WriteString

func (w *Writer) WriteString(str string) (err error)

WriteString to stream

func (*Writer) WriteStringWithRef

func (w *Writer) WriteStringWithRef(str string) (err error)

WriteStringWithRef to stream

func (*Writer) WriteTime

func (w *Writer) WriteTime(t time.Time) (err error)

WriteTime to stream

func (*Writer) WriteUint64

func (w *Writer) WriteUint64(v uint64) (err error)

WriteUint64 to stream

func (*Writer) WriteValue

func (w *Writer) WriteValue(v reflect.Value) (err error)

WriteValue to stream

Directories

Path Synopsis
Package hprose client example: package main import ( "fmt" "hprose" ) type testUser struct { Name string Sex int Birthday time.Time Age int Married bool } type testRemoteObject struct { Hello func(string) string HelloWithError func(string) (string, error) `name:"hello"` AsyncHello func(string) <-chan string `name:"hello"` AsyncHelloWithError func(string) (<-chan string, <-chan error) `name:"hello"` Sum func(...int) int SwapKeyAndValue func(*map[string]string) map[string]string `byref:"true"` SwapInt func(int, int) (int, int) `name:"swap"` SwapFloat func(float64, float64) (float64, float64) `name:"swap"` Swap func(interface{}, interface{}) (interface{}, interface{}) GetUserList func() []testUser } func main() { client := hprose.NewClient("http://www.hprose.com/example/") var ro *RemoteObject client.UseService(&ro) // If an error occurs, it will panic fmt.Println(ro.Hello("World")) // If an error occurs, an error value will be returned if result, err := ro.HelloWithError("World"); err == nil { fmt.Println(result) } else { fmt.Println(err.Error()) } // If an error occurs, it will be ignored result := ro.AsyncHello("World") fmt.Println(<-result) // If an error occurs, an error chan will be returned result, err := ro.AsyncHelloWithError("World") if e := <-err; e == nil { fmt.Println(<-result) } else { fmt.Println(e.Error()) } fmt.Println(ro.Sum(1, 2, 3, 4, 5)) m := make(map[string]string) m["Jan"] = "January" m["Feb"] = "February" m["Mar"] = "March" m["Apr"] = "April" m["May"] = "May" m["Jun"] = "June" m["Jul"] = "July" m["Aug"] = "August" m["Sep"] = "September" m["Oct"] = "October" m["Nov"] = "November" m["Dec"] = "December" fmt.Println(m) mm := ro.SwapKeyAndValue(&m) fmt.Println(m) fmt.Println(mm) fmt.Println(ro.GetUserList()) fmt.Println(ro.SwapInt(1, 2)) fmt.Println(ro.SwapFloat(1.2, 3.4)) fmt.Println(ro.Swap("Hello", "World")) }
Package hprose client example: package main import ( "fmt" "hprose" ) type testUser struct { Name string Sex int Birthday time.Time Age int Married bool } type testRemoteObject struct { Hello func(string) string HelloWithError func(string) (string, error) `name:"hello"` AsyncHello func(string) <-chan string `name:"hello"` AsyncHelloWithError func(string) (<-chan string, <-chan error) `name:"hello"` Sum func(...int) int SwapKeyAndValue func(*map[string]string) map[string]string `byref:"true"` SwapInt func(int, int) (int, int) `name:"swap"` SwapFloat func(float64, float64) (float64, float64) `name:"swap"` Swap func(interface{}, interface{}) (interface{}, interface{}) GetUserList func() []testUser } func main() { client := hprose.NewClient("http://www.hprose.com/example/") var ro *RemoteObject client.UseService(&ro) // If an error occurs, it will panic fmt.Println(ro.Hello("World")) // If an error occurs, an error value will be returned if result, err := ro.HelloWithError("World"); err == nil { fmt.Println(result) } else { fmt.Println(err.Error()) } // If an error occurs, it will be ignored result := ro.AsyncHello("World") fmt.Println(<-result) // If an error occurs, an error chan will be returned result, err := ro.AsyncHelloWithError("World") if e := <-err; e == nil { fmt.Println(<-result) } else { fmt.Println(e.Error()) } fmt.Println(ro.Sum(1, 2, 3, 4, 5)) m := make(map[string]string) m["Jan"] = "January" m["Feb"] = "February" m["Mar"] = "March" m["Apr"] = "April" m["May"] = "May" m["Jun"] = "June" m["Jul"] = "July" m["Aug"] = "August" m["Sep"] = "September" m["Oct"] = "October" m["Nov"] = "November" m["Dec"] = "December" fmt.Println(m) mm := ro.SwapKeyAndValue(&m) fmt.Println(m) fmt.Println(mm) fmt.Println(ro.GetUserList()) fmt.Println(ro.SwapInt(1, 2)) fmt.Println(ro.SwapFloat(1.2, 3.4)) fmt.Println(ro.Swap("Hello", "World")) }

Jump to

Keyboard shortcuts

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