goapplib

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: May 1, 2024 License: MIT Imports: 14 Imported by: 0

README

goapplib

Provide a library that can be called by mobile or desktop applications. It starts a local TCP server to facilitate communication between your application and a backend written in Golang.

Usage

SDK

You must refer to the example code in example to write your SDK code.

Application
import 'dart:ffi' as ffi;
import 'dart:io';

var responseMap = <String, Completer>{};

void onReceiveResponse(List<int> data) {
    String str = String.fromCharCodes(data);
    var map = json.decode(str);
    String traceId = map['traceId'];
    Completer completer = responseMap[traceId];
    if (completer != null) {
        completer.complete(map['data']);
    }
}

Map<String, dynamic> onReceiveRequest(List<int> data) {
    // json data to map
    String str = String.fromCharCodes(data);
    var map = json.decode(str);
    return {
        'code': 0,
        'traceId': map['traceId'],
        'data': map['data'],
    };
}

Map<String, dynamic> sendRequest(Socket socket, Map<String, dynamic> data) async {
    // 1. generate traceId
    String traceId = Uuid().v4();
    // 2. create completer
    Completer completer = Completer();
    // 3. add completer to responseMap
    responseMap[traceId] = completer;
    // 4. send request
    Map<String, dynamic> request = {
        'traceId': traceId,
        'data': data,
    };
    String requestStr = json.encode(request);
    List<int> requestBytes = utf8.encode(requestStr);
    int dataLength = requestBytes.length;
    List<int> dataLengthBytes = [
        dataLength >> 24 & 0xFF,
        dataLength >> 16 & 0xFF,
        dataLength >> 8 & 0xFF,
        dataLength & 0xFF,
    ];
    List<int> message = [
        ...dataLengthBytes,
        0,
        ...requestBytes,
    ];
    socket.add(message);
    // 5. wait for response
    Map<String, dynamic> response = await completer.future;
    // 6. remove completer from responseMap
    responseMap.remove(traceId);
    // 7. return response
    return response;
}

void main() async {
    // 1. 加载动态库
    ffi.DynamicLibrary dylib = ffi.DynamicLibrary.open('libgoapplib.dylib');
    // 2. Get Local Tcp Address
    ffi.Pointer<Utf8> Function() getLocalTcpAddress =
        dylib.lookup<ffi.NativeFunction<ffi.Pointer<Utf8> Function()>>(
            'Address').asFunction();
    ffi.Pointer<Utf8> address = getLocalTcpAddress();
    String localTcpAddress = ffi.Utf8.fromUtf8(address);
    print('localTcpAddress: $localTcpAddress');
    // 3. get host and port
    List<String> hostAndPort = localTcpAddress.split(':');
    String host = hostAndPort[0];
    int port = int.parse(hostAndPort[1]);
    // 4. connect to local tcp server
    Socket socket = await Socket.connect(host, port);
    // 5. set listener
    var dataBuffer = <int>[];
    socket.listen((List<int> event) {
        // message: [4]DataLength + [1]IsResponse + [n]Data
        dataBuffer.addAll(event);
        while (dataBuffer.length >= 5) {
            int dataLength = dataBuffer[0] << 24 |
                dataBuffer[1] << 16 |
                dataBuffer[2] << 8 |
                dataBuffer[3];
            if (dataBuffer.length >= dataLength + 4) {
                bool isResponse = dataBuffer[4] == 1;
                List<int> data = dataBuffer.sublist(5, dataLength + 4);
                dataBuffer = dataBuffer.sublist(dataLength + 4);
                if (isResponse) {
                    // response
                    onReceiveResponse(data);
                } else {
                    // request
                    print('request: ${String.fromCharCodes(data)}');
                    // response
                    onReceiveRequest(data);
                }
            } else {
                break;
            }
        }
    });
    // 6. test send request
    var resp = await sendRequest(socket, {
        'method': 'test',
        'data': 'hello',
    });
    print('resp: $resp');
    // 7. close socket
    socket.close();
}

Documentation

Index

Constants

View Source
const (
	Version = "v0.0.4"
)

Variables

View Source
var (
	Code_name = map[int32]string{
		0:   "OK",
		400: "InvalidRequest",
		404: "MethodNotFound",
		500: "InternalError",
		501: "MethodNullResponse",
	}
	Code_value = map[string]int32{
		"OK":                 0,
		"InvalidRequest":     400,
		"MethodNotFound":     404,
		"InternalError":      500,
		"MethodNullResponse": 501,
	}
)

Enum value maps for Code.

View Source
var File_goapplib_calling_proto protoreflect.FileDescriptor

Functions

func Address

func Address() string

func Init

func Init(c *LocalServerConfig)

Types

type Callback

type Callback interface {
	OnAppCall(ctx context.Context, request *GoRequest) (response *GoResponse)
	OnAppReady()
	OnAppClose()
}

type Code

type Code int32
const (
	Code_OK                 Code = 0
	Code_InvalidRequest     Code = 400
	Code_MethodNotFound     Code = 404
	Code_InternalError      Code = 500
	Code_MethodNullResponse Code = 501
	Code_Canceled           Code = 600
)

func (Code) Descriptor added in v0.0.5

func (Code) Descriptor() protoreflect.EnumDescriptor

func (Code) Enum added in v0.0.5

func (x Code) Enum() *Code

func (Code) EnumDescriptor deprecated added in v0.0.5

func (Code) EnumDescriptor() ([]byte, []int)

Deprecated: Use Code.Descriptor instead.

func (Code) Number added in v0.0.5

func (x Code) Number() protoreflect.EnumNumber

func (Code) String added in v0.0.5

func (x Code) String() string

func (Code) Type added in v0.0.5

func (Code) Type() protoreflect.EnumType

type GoRequest added in v0.0.5

type GoRequest struct {
	TraceId string `protobuf:"bytes,1,opt,name=traceId,proto3" json:"traceId,omitempty"`
	Method  string `protobuf:"bytes,2,opt,name=method,proto3" json:"method,omitempty"`
	Data    []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"`
	// contains filtered or unexported fields
}

func (*GoRequest) Descriptor deprecated added in v0.0.5

func (*GoRequest) Descriptor() ([]byte, []int)

Deprecated: Use GoRequest.ProtoReflect.Descriptor instead.

func (*GoRequest) GetData added in v0.0.5

func (x *GoRequest) GetData() []byte

func (*GoRequest) GetMethod added in v0.0.5

func (x *GoRequest) GetMethod() string

func (*GoRequest) GetTraceId added in v0.0.5

func (x *GoRequest) GetTraceId() string

func (*GoRequest) Marshal added in v0.0.5

func (r *GoRequest) Marshal() []byte

func (*GoRequest) ProtoMessage added in v0.0.5

func (*GoRequest) ProtoMessage()

func (*GoRequest) ProtoReflect added in v0.0.5

func (x *GoRequest) ProtoReflect() protoreflect.Message

func (*GoRequest) Reset added in v0.0.5

func (x *GoRequest) Reset()

func (*GoRequest) String added in v0.0.5

func (x *GoRequest) String() string

func (*GoRequest) Unmarshal added in v0.0.5

func (r *GoRequest) Unmarshal(data []byte) error

type GoResponse added in v0.0.5

type GoResponse struct {
	TraceId string `protobuf:"bytes,1,opt,name=traceId,proto3" json:"traceId,omitempty"`
	Code    Code   `protobuf:"varint,2,opt,name=code,proto3,enum=goapplib.Code" json:"code,omitempty"`
	Data    []byte `protobuf:"bytes,3,opt,name=data,proto3" json:"data,omitempty"`
	// contains filtered or unexported fields
}

func CallApp

func CallApp(req *GoRequest) *GoResponse

func (*GoResponse) Descriptor deprecated added in v0.0.5

func (*GoResponse) Descriptor() ([]byte, []int)

Deprecated: Use GoResponse.ProtoReflect.Descriptor instead.

func (*GoResponse) GetCode added in v0.0.5

func (x *GoResponse) GetCode() Code

func (*GoResponse) GetData added in v0.0.5

func (x *GoResponse) GetData() []byte

func (*GoResponse) GetTraceId added in v0.0.5

func (x *GoResponse) GetTraceId() string

func (*GoResponse) Marshal added in v0.0.5

func (r *GoResponse) Marshal() []byte

func (*GoResponse) ProtoMessage added in v0.0.5

func (*GoResponse) ProtoMessage()

func (*GoResponse) ProtoReflect added in v0.0.5

func (x *GoResponse) ProtoReflect() protoreflect.Message

func (*GoResponse) Reset added in v0.0.5

func (x *GoResponse) Reset()

func (*GoResponse) String added in v0.0.5

func (x *GoResponse) String() string

func (*GoResponse) Unmarshal added in v0.0.5

func (r *GoResponse) Unmarshal(data []byte) error

type LocalServer

type LocalServer struct {
	Config *LocalServerConfig
	// contains filtered or unexported fields
}

func NewLocalServer

func NewLocalServer(config *LocalServerConfig) *LocalServer

func (*LocalServer) Start

func (l *LocalServer) Start()

type LocalServerConfig

type LocalServerConfig struct {
	Address  string
	Callback Callback
}

func DefaultLocalServerConfig

func DefaultLocalServerConfig() *LocalServerConfig

type StatusError added in v0.0.5

type StatusError struct {
	Code    Code   `json:"code"`
	Message string `json:"message"`
}

func ErrorAsStatusError added in v0.0.5

func ErrorAsStatusError(err error) (*StatusError, bool)

func NewStatusError added in v0.0.5

func NewStatusError(code Code, message string) *StatusError

func NewStatusErrorFromError added in v0.0.5

func NewStatusErrorFromError(code Code, err error) *StatusError

func NewStatusErrorf added in v0.0.5

func NewStatusErrorf(code Code, format string, args ...interface{}) *StatusError

func (*StatusError) Error added in v0.0.5

func (e *StatusError) Error() string

Directories

Path Synopsis
cmd
cgo command
testing command
version command

Jump to

Keyboard shortcuts

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