lcsc

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2026 License: MIT Imports: 16 Imported by: 0

README

go-lcsc

Go Reference Go Report Card Tests

Unofficial Go client for LCSC component search and product details.

LCSC does not provide a documented public API for this data. This library uses undocumented endpoints that can change without notice.

Requirements

  • Go 1.22+
  • No external dependencies (stdlib only)

Installation

go get github.com/PatrickWalther/go-lcsc

Quick Start

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/PatrickWalther/go-lcsc"
)

func main() {
	client := lcsc.NewClient(
		lcsc.WithCurrency("USD"),
		lcsc.WithRateLimit(5),
	)
	defer client.Close()

	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
	defer cancel()

	search, err := client.Search.Keyword(ctx, &lcsc.SearchRequest{
		Keyword: "STM32F103",
	})
	if err != nil {
		log.Fatal(err)
	}

	if len(search.Products) == 0 {
		log.Fatal("no products found")
	}

	product, err := client.Product.Details(ctx, search.Products[0].ProductCode)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s - %s\n", product.ProductCode, product.ProductModel)
	fmt.Printf("Stock: %d\n", product.StockNumber)
}

Features

  • Service-based API: client.Search and client.Product
  • Automatic retries with exponential backoff for transient failures
  • Token-bucket request rate limiting
  • Optional in-memory response caching with configurable TTL
  • Typed errors with errors.Is/errors.As support
  • Thread-safe client for concurrent use

API

Search Service
resp, err := client.Search.Keyword(ctx, &lcsc.SearchRequest{
	Keyword: "CGJ2B2C0G1H390J050BA",
})

for _, p := range resp.Products {
	fmt.Println(p.ProductCode, p.ProductModel)
}

if resp.DirectMatchCode != "" {
	fmt.Println("direct match:", resp.DirectMatchCode)
}
Product Service
product, err := client.Product.Details(ctx, "C8734")
if err != nil {
	// handle error
}

fmt.Println(product.ProductCode)
fmt.Println(product.ProductModel)
fmt.Println(product.BrandNameEn)
fmt.Println(product.PdfURL)
fmt.Println(product.GetProductURL())

Configuration Options

client := lcsc.NewClient(
	lcsc.WithHTTPClient(&http.Client{Timeout: 60 * time.Second}),
	lcsc.WithBaseURL("https://wmsc.lcsc.com/ftps/wm"),
	lcsc.WithCurrency("EUR"),
	lcsc.WithRateLimit(10),
	lcsc.WithCache(lcsc.NewMemoryCache(10*time.Minute)),
	lcsc.WithCacheConfig(lcsc.CacheConfig{
		Enabled:    true,
		SearchTTL:  2 * time.Minute,
		DetailsTTL: 5 * time.Minute,
	}),
	lcsc.WithRetryConfig(lcsc.RetryConfig{
		MaxRetries:     5,
		InitialBackoff: 300 * time.Millisecond,
		MaxBackoff:     10 * time.Second,
		Multiplier:     2.0,
		Jitter:         0.1,
	}),
)
defer client.Close()
Cache Controls
client := lcsc.NewClient()
defer client.Close()

client.ClearCache()

clientNoCache := lcsc.NewClient(lcsc.WithoutCache())
defer clientNoCache.Close()
Retry Controls
client := lcsc.NewClient(lcsc.WithoutRetry())
defer client.Close()

Error Handling

import "errors"

_, err := client.Product.Details(ctx, "C99999999")
if err != nil {
	if errors.Is(err, lcsc.ErrInvalidRequest) {
		// bad input
	}
	if errors.Is(err, lcsc.ErrNotFound) {
		// no component found
	}
	if errors.Is(err, lcsc.ErrRateLimited) {
		// upstream rate limited
	}
	if errors.Is(err, lcsc.ErrServer) {
		// upstream server failure
	}

	var apiErr *lcsc.APIError
	if errors.As(err, &apiErr) {
		fmt.Println(apiErr.StatusCode, apiErr.Code, apiErr.Message)
	}
}

Breaking Changes In v1.0.0

  • Removed flat client methods:
    • client.KeywordSearch(...)
    • client.GetProductDetails(...)
  • Replaced with service methods:
    • client.Search.Keyword(...)
    • client.Product.Details(...)
  • Removed legacy search request fields that were ignored by the upstream endpoint.
  • Standardized errors to:
    • ErrInvalidRequest
    • ErrNotFound
    • ErrRateLimited
    • ErrServer
  • Product struct field names standardized to Go initialisms:
    • PdfUrl -> PdfURL
    • ProductImageUrl -> ProductImageURL

Testing

Unit tests
go test ./...
Integration tests (real LCSC API)
go test -tags=integration -run Integration ./...

License

MIT - see LICENSE.

Documentation

Overview

Package lcsc provides an unofficial Go client for LCSC component data.

Endpoints are organized into service groups:

  • client.Search - keyword search
  • client.Product - product details

LCSC does not provide an official public API for this data. This package uses undocumented endpoints discovered from the web application and they can change without notice.

Index

Constants

View Source
const Version = "1.0.0"

Version is the current version of the go-lcsc package.

Variables

View Source
var (
	// ErrInvalidRequest indicates an invalid client request.
	ErrInvalidRequest = errors.New("lcsc: invalid request")

	// ErrNotFound indicates the requested resource was not found.
	ErrNotFound = errors.New("lcsc: not found")

	// ErrRateLimited indicates the API rate limit has been exceeded.
	ErrRateLimited = errors.New("lcsc: rate limit exceeded")

	// ErrServer indicates a server-side API failure.
	ErrServer = errors.New("lcsc: server error")
)

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode int
	Code       int
	Message    string
	Details    string
}

APIError represents an error returned by the LCSC API.

func (*APIError) Error

func (e *APIError) Error() string

func (*APIError) Unwrap added in v1.0.0

func (e *APIError) Unwrap() error

Unwrap enables errors.Is checks for common failure classes.

type Cache

type Cache interface {
	Get(key string) ([]byte, bool)
	Set(key string, value []byte, ttl time.Duration)
	Delete(key string)
}

Cache defines the interface for caching API responses.

type CacheConfig

type CacheConfig struct {
	Enabled    bool
	SearchTTL  time.Duration // TTL for search results (default 5 min)
	DetailsTTL time.Duration // TTL for product details (default 10 min)
}

CacheConfig configures caching behavior.

func DefaultCacheConfig

func DefaultCacheConfig() CacheConfig

DefaultCacheConfig returns the default cache configuration.

type Client

type Client struct {
	Search  *SearchService
	Product *ProductService
	// contains filtered or unexported fields
}

Client is an LCSC API client.

func NewClient

func NewClient(opts ...ClientOption) *Client

NewClient creates a new LCSC API client.

func (*Client) ClearCache added in v1.0.0

func (c *Client) ClearCache()

ClearCache clears all cached responses in the default memory cache.

func (*Client) Close added in v1.0.0

func (c *Client) Close() error

Close releases resources held by the client.

type ClientOption

type ClientOption func(*Client)

ClientOption configures a Client.

func WithBaseURL

func WithBaseURL(baseURL string) ClientOption

WithBaseURL sets a custom base URL.

func WithCache

func WithCache(cache Cache) ClientOption

WithCache sets a custom cache implementation.

func WithCacheConfig added in v1.0.0

func WithCacheConfig(config CacheConfig) ClientOption

WithCacheConfig sets the cache configuration.

func WithCurrency

func WithCurrency(currency string) ClientOption

WithCurrency sets the currency for price responses.

func WithHTTPClient

func WithHTTPClient(httpClient *http.Client) ClientOption

WithHTTPClient sets a custom HTTP client.

func WithRateLimit

func WithRateLimit(rps float64) ClientOption

WithRateLimit sets a custom rate limit (requests per second).

func WithRetryConfig

func WithRetryConfig(config RetryConfig) ClientOption

WithRetryConfig sets the retry configuration.

func WithoutCache added in v1.0.0

func WithoutCache() ClientOption

WithoutCache disables response caching.

func WithoutRetry added in v1.0.0

func WithoutRetry() ClientOption

WithoutRetry disables retries.

type FlexFloat64

type FlexFloat64 float64

FlexFloat64 handles JSON values that may be either a number or a string.

func (*FlexFloat64) UnmarshalJSON

func (f *FlexFloat64) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for FlexFloat64.

type MemoryCache

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

MemoryCache is a simple in-memory cache with TTL support.

func NewMemoryCache

func NewMemoryCache(defaultTTL time.Duration) *MemoryCache

NewMemoryCache creates a new in-memory cache with the specified default TTL.

func (*MemoryCache) Clear

func (c *MemoryCache) Clear()

Clear removes all entries from the cache.

func (*MemoryCache) Close added in v0.1.2

func (c *MemoryCache) Close()

Close stops the cleanup goroutine.

func (*MemoryCache) Delete

func (c *MemoryCache) Delete(key string)

Delete removes a value from the cache.

func (*MemoryCache) Get

func (c *MemoryCache) Get(key string) ([]byte, bool)

Get retrieves a value from the cache.

func (*MemoryCache) Set

func (c *MemoryCache) Set(key string, value []byte, ttl time.Duration)

Set stores a value in the cache with the specified TTL. If ttl is 0, the default TTL is used.

func (*MemoryCache) Size

func (c *MemoryCache) Size() int

Size returns the number of entries in the cache.

type Parameter

type Parameter struct {
	ParamNameEn  string `json:"paramNameEn"`
	ParamValueEn string `json:"paramValueEn"`
}

Parameter represents a product specification.

type PriceBreak

type PriceBreak struct {
	Ladder         int         `json:"ladder"`
	ProductPrice   FlexFloat64 `json:"productPrice"`
	CurrencySymbol string      `json:"currencySymbol"`
}

PriceBreak represents a quantity-based price tier.

type Product

type Product struct {
	ProductCode       string       `json:"productCode"`
	ProductModel      string       `json:"productModel"`
	BrandNameEn       string       `json:"brandNameEn"`
	ProductIntroEn    string       `json:"productIntroEn"`
	PdfURL            string       `json:"pdfUrl"`
	ProductImages     []string     `json:"productImages"`
	ProductImageURL   string       `json:"productImageUrl"`
	StockNumber       int          `json:"stockNumber"`
	MinPacketNumber   int          `json:"minPacketNumber"`
	ProductPriceList  []PriceBreak `json:"productPriceList"`
	ParamVOList       []Parameter  `json:"paramVOList"`
	EncapStandard     string       `json:"encapStandard"`
	ParentCatalogName string       `json:"parentCatalogName"`
	CatalogName       string       `json:"catalogName"`
	Weight            float64      `json:"weight"`
}

Product represents an LCSC component.

func (*Product) GetProductURL

func (p *Product) GetProductURL() string

GetProductURL returns the LCSC product page URL.

type ProductService added in v1.0.0

type ProductService service

ProductService handles product-detail operations.

func (*ProductService) Details added in v1.0.0

func (s *ProductService) Details(ctx context.Context, productCode string) (*Product, error)

Details retrieves detailed information for a specific product code.

type RateLimiter

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

RateLimiter implements a token bucket rate limiter.

func NewRateLimiter

func NewRateLimiter(requestsPerSecond float64) *RateLimiter

NewRateLimiter creates a new rate limiter with the specified requests per second.

func (*RateLimiter) Wait

func (r *RateLimiter) Wait(ctx context.Context) error

Wait blocks until a token is available or the context is cancelled.

type RetryConfig

type RetryConfig struct {
	MaxRetries     int           // Maximum number of retry attempts (default 3)
	InitialBackoff time.Duration // Initial backoff duration (default 500ms)
	MaxBackoff     time.Duration // Maximum backoff duration (default 30s)
	Multiplier     float64       // Backoff multiplier (default 2.0)
	Jitter         float64       // Random jitter factor 0-1 (default 0.1)
}

RetryConfig configures retry behavior.

func DefaultRetryConfig

func DefaultRetryConfig() RetryConfig

DefaultRetryConfig returns the default retry configuration.

func NoRetry

func NoRetry() RetryConfig

NoRetry returns a configuration that disables retries.

type SearchRequest

type SearchRequest struct {
	Keyword string
}

SearchRequest contains parameters for product search.

type SearchResponse

type SearchResponse struct {
	Products        []Product
	TotalCount      int
	DirectMatchCode string
}

SearchResponse contains product search results.

type SearchService added in v1.0.0

type SearchService service

SearchService handles product search operations.

func (*SearchService) Keyword added in v1.0.0

func (s *SearchService) Keyword(ctx context.Context, req *SearchRequest) (*SearchResponse, error)

Keyword searches for products by keyword.

Jump to

Keyboard shortcuts

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