springcloud

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2024 License: Apache-2.0 Imports: 18 Imported by: 1

README ¶

spring-cloud-go

License Language version Godoc Go report codecov

📋 Requirements

  • Go 1.21+

🚀 Install

go get github.com/libgox/spring-cloud-go

💡 Usage

Zookeeper Discovery Setup
package main

import (
	"fmt"
	"log"

	"github.com/libgox/addr"
	springcloud "github.com/libgox/spring-cloud-go"
	"github.com/protocol-laboratory/zookeeper-client-go/zk"
)

func main() {
	config := &springcloud.ZooKeeperDiscoveryConfig{
		ZkConfig: &zk.Config{
			Addresses: []addr.Address{
				{
					Host: "localhost",
					Port: 2181,
				},
			},
		},
	}

	discovery, err := springcloud.NewZookeeperDiscovery(config)
	if err != nil {
		log.Fatalf("Failed to initialize discovery: %v", err)
	}

	endpoints, err := discovery.GetEndpoints("springcloud-service")
	if err != nil {
		log.Fatalf("Failed to get endpoints: %v", err)
	}

	fmt.Println("Discovered endpoints:", endpoints)
	defer discovery.Close()
}

To add the spring_cloud_client section to your README, you can introduce it as a feature of your spring-cloud-go library that allows for seamless HTTP client communication using service discovery. Here's a suggestion on how to structure this new section:


Spring Cloud Client Setup

The spring_cloud_client package in spring-cloud-go enables HTTP-based communication between services, leveraging Spring Cloud's service discovery mechanism.

Example Usage
package main

import (
	"context"
	"fmt"
	"github.com/libgox/addr"
	"io/ioutil"
	"log"

	"crypto/tls"
	springcloud "github.com/libgox/spring-cloud-go"
	"github.com/protocol-laboratory/zookeeper-client-go/zk"
)

func main() {
	// Initialize ZooKeeper discovery
	discoveryConfig := &springcloud.ZooKeeperDiscoveryConfig{
		ZkConfig: &zk.Config{
			Addresses: []addr.Address{
				{
					Host: "localhost",
					Port: 2181,
				},
			},
		},
	}

	discovery, err := springcloud.NewZookeeperDiscovery(discoveryConfig)
	if err != nil {
		log.Fatalf("Failed to initialize discovery: %v", err)
	}
	defer discovery.Close()

	// Set up the client configuration
	clientConfig := springcloud.ClientConfig{
		Discovery: discovery,
		TlsConfig: &tls.Config{InsecureSkipVerify: true}, // Optionally configure TLS
	}

	// Create a new client
	client := springcloud.NewClient(clientConfig)

	// Make a GET request to a discovered service
	resp, err := client.Get(context.Background(), "springcloud-service", "/path/to/resource", nil)
	if err != nil {
		log.Fatalf("Failed to perform GET request: %v", err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalf("Failed to read response body: %v", err)
	}

	fmt.Println("Response:", string(body))
}
Key Features:
  • Service Discovery Integration: Automatically discover services registered in Zookeeper.
  • Load Balancing: Client requests are distributed across available endpoints using a round-robin strategy.
  • Flexible HTTP Methods: Supports GET, POST, PUT, and DELETE HTTP methods for interacting with services.
  • TLS Support: Optional TLS configuration for secure service communication.
Available Methods
  • client.Get: Sends an HTTP GET request.
  • client.Post: Sends an HTTP POST request with a body.
  • client.Put: Sends an HTTP PUT request with a body.
  • client.Delete: Sends an HTTP DELETE request.

Documentation ¶

Index ¶

Constants ¶

View Source
const (
	LogKeyData      = "data"
	LogKeyError     = "error"
	LogKeyIp        = "ip"
	LogKeyIps       = "ips"
	LogKeyEndpoints = "endpoints"
	LogKeyPath      = "path"
	LogKeyService   = "service"
)
View Source
const (
	HeaderAccept      = "Accept"
	HeaderContentType = "Content-Type"
)
View Source
const (
	MediaJson = "application/json"
	MediaXml  = "application/xml"
)

Variables ¶

View Source
var (
	ErrNoAvailableEndpoint = errors.New("no available endpoint")
)

Functions ¶

This section is empty.

Types ¶

type Client ¶

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

func NewClient ¶

func NewClient(config ClientConfig) *Client

func (*Client) Delete ¶

func (c *Client) Delete(ctx context.Context, serviceName string, path string, headers textproto.MIMEHeader) (*http.Response, error)

func (*Client) Get ¶

func (c *Client) Get(ctx context.Context, serviceName string, path string, headers textproto.MIMEHeader) (*http.Response, error)

func (*Client) JsonDelete ¶ added in v0.0.2

func (c *Client) JsonDelete(ctx context.Context, serviceName, path string, headers textproto.MIMEHeader) error

JsonDelete sends a DELETE request and automatically handles JSON response unmarshalling

func (*Client) JsonGet ¶ added in v0.0.2

func (c *Client) JsonGet(ctx context.Context, serviceName, path string, headers textproto.MIMEHeader, respObj any) error

JsonGet sends a GET request and automatically handles JSON response unmarshalling

func (*Client) JsonPost ¶ added in v0.0.2

func (c *Client) JsonPost(ctx context.Context, serviceName, path string, reqObj any, headers textproto.MIMEHeader, respObj any) error

JsonPost sends a POST request with JSON marshalling of the request body and JSON unmarshalling of the response

func (*Client) JsonPut ¶ added in v0.0.2

func (c *Client) JsonPut(ctx context.Context, serviceName, path string, reqObj any, headers textproto.MIMEHeader, respObj any) error

JsonPut sends a PUT request with JSON marshalling of the request body and JSON unmarshalling of the response

func (*Client) JsonRequest ¶ added in v0.0.2

func (c *Client) JsonRequest(ctx context.Context, serviceName, method, path string, body []byte, headers textproto.MIMEHeader, respObj any) error

JsonRequest handles making a request, sending JSON data, and automatically unmarshalling the JSON response

func (*Client) Post ¶

func (c *Client) Post(ctx context.Context, serviceName string, path string, body []byte, headers textproto.MIMEHeader) (*http.Response, error)

func (*Client) Put ¶

func (c *Client) Put(ctx context.Context, serviceName string, path string, body []byte, headers textproto.MIMEHeader) (*http.Response, error)

func (*Client) Request ¶

func (c *Client) Request(ctx context.Context, serviceName string, method string, path string, body []byte, headers textproto.MIMEHeader) (*http.Response, error)

func (*Client) XmlDelete ¶ added in v0.1.0

func (c *Client) XmlDelete(ctx context.Context, serviceName, path string, headers textproto.MIMEHeader) error

XmlDelete sends a DELETE request and automatically handles XML response unmarshalling

func (*Client) XmlGet ¶ added in v0.1.0

func (c *Client) XmlGet(ctx context.Context, serviceName, path string, headers textproto.MIMEHeader, respObj any) error

XmlGet sends a GET request and automatically handles XML response unmarshalling

func (*Client) XmlPost ¶ added in v0.1.0

func (c *Client) XmlPost(ctx context.Context, serviceName, path string, reqObj any, headers textproto.MIMEHeader, respObj any) error

XmlPost sends a POST request with XML marshalling of the request body and XML unmarshalling of the response

func (*Client) XmlPut ¶ added in v0.1.0

func (c *Client) XmlPut(ctx context.Context, serviceName, path string, reqObj any, headers textproto.MIMEHeader, respObj any) error

XmlPut sends a PUT request with XML marshalling of the request body and XML unmarshalling of the response

func (*Client) XmlRequest ¶ added in v0.1.0

func (c *Client) XmlRequest(ctx context.Context, serviceName, method, path string, body []byte, headers textproto.MIMEHeader, respObj any) error

XmlRequest handles making a request, sending XML data, and automatically unmarshalling the XML response

type ClientConfig ¶

type ClientConfig struct {
	Discovery Discovery
	// TlsConfig configuration information for tls.
	TlsConfig *tls.Config
	// Timeout default 30s
	Timeout time.Duration
	// ConnectTimeout default 10s
	ConnectTimeout time.Duration
	// Logger structured logger for logging operations
	Logger *slog.Logger
}

type Discovery ¶

type Discovery interface {
	GetEndpoints(serviceName string) ([]*Endpoint, error)

	Close() error
}

type Endpoint ¶

type Endpoint struct {
	Name                string      `json:"name"`
	Id                  string      `json:"id"`
	Address             string      `json:"address"`
	Port                int         `json:"port"`
	SslPort             *int        `json:"sslPort"`
	Payload             interface{} `json:"payload"`
	RegistrationTimeUTC int64       `json:"registrationTimeUTC"`
	ServiceType         string      `json:"serviceType"`
	UriSpec             UriSpec     `json:"uriSpec"`
}

type HttpStatusError ¶ added in v0.1.0

type HttpStatusError struct {
	StatusCode int
	StatusText string
	Body       string
}

func NewHttpStatusError ¶ added in v0.1.0

func NewHttpStatusError(statusCode int, body string) *HttpStatusError

func (*HttpStatusError) Error ¶ added in v0.1.0

func (e *HttpStatusError) Error() string

func (*HttpStatusError) Is ¶ added in v0.1.0

func (e *HttpStatusError) Is(target error) bool

type Part ¶ added in v0.2.1

type Part struct {
	Value    string `json:"value"`
	Variable bool   `json:"variable"`
}

type UriSpec ¶ added in v0.2.0

type UriSpec struct {
	Parts []Part `json:"parts"`
}

type ZooKeeperDiscoveryConfig ¶

type ZooKeeperDiscoveryConfig struct {
	ZkConfig *zk.Config

	// Logger structured logger for logging operations
	Logger *slog.Logger
}

type ZookeeperDiscovery ¶

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

func NewZookeeperDiscovery ¶

func NewZookeeperDiscovery(config *ZooKeeperDiscoveryConfig) (*ZookeeperDiscovery, error)

func (*ZookeeperDiscovery) Close ¶

func (z *ZookeeperDiscovery) Close() error

func (*ZookeeperDiscovery) GetEndpoints ¶

func (z *ZookeeperDiscovery) GetEndpoints(serviceName string) ([]*Endpoint, error)

Jump to

Keyboard shortcuts

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