newtqnia

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2026 License: MIT Imports: 12 Imported by: 0

README

NewTqnia Go SDK

CI Go Reference Go Report Card License

The official, dependency-free Go SDK for the NewTqnia technology news API. It provides typed English and Arabic news, context.Context cancellation, request timeouts, automatic retries, Retry-After support, typed errors, and configurable HTTP transports.

When displaying API content, preserve returned article URLs and visibly render the attribution supplied in the response—normally Powered by NewTqnia.

Requirements and installation

Go 1.22 or newer:

go get github.com/newtqnia/newtqnia-go@latest

Quick start

package main

import (
    "context"
    "fmt"
    "log"

    newtqnia "github.com/newtqnia/newtqnia-go"
)

func main() {
    client := newtqnia.New()
    digest, err := client.News.Latest(context.Background(), &newtqnia.NewsListParams{
        Locale: newtqnia.LocaleEnglish,
        Limit:  5,
    })
    if err != nil {
        log.Fatal(err)
    }

    for _, article := range digest.Articles {
        fmt.Println(article.Title, article.URL)
    }
    fmt.Println(digest.Attribution.Text, digest.Attribution.URL)
}

The API currently exposes only the two collections in NewTqnia's OpenAPI contract:

today, err := client.News.Today(ctx, &newtqnia.NewsListParams{Locale: newtqnia.LocaleArabic})
latest, err := client.News.Latest(ctx, &newtqnia.NewsListParams{Category: "ai", Limit: 10})

Free-text search, individual article lookup, category listing, and pagination are not currently part of the public API, so the SDK does not invent those operations.

Authentication and identification

No API key is required. If you have an optional key from your NewTqnia profile, configure it along with optional application identification:

client, err := newtqnia.NewClient(newtqnia.Config{
    APIKey:      os.Getenv("NEWTQNIA_API_KEY"),
    Application: "editorial-dashboard",
    Website:     "https://example.com",
})

The key is sent as X-API-Key; it is never placed in the URL or an Authorization header.

Configuration

client, err := newtqnia.NewClient(newtqnia.Config{
    BaseURL:   "https://api.newtqnia.com",
    Timeout:   15 * time.Second,
    UserAgent: "my-service/2.0",
    Retry: newtqnia.RetryConfig{
        MaxRetries:  3,
        InitialWait: 500 * time.Millisecond,
        MaxWait:     8 * time.Second,
    },
    HTTPClient: &http.Client{Transport: customTransport},
    Headers:    http.Header{"X-Trace-Source": {"my-service"}},
})

The default is a 30-second timeout and two retries after the initial request. Retries use exponential backoff for temporary network failures and HTTP 429, 500, 502, 503, and 504 responses. Server Retry-After instructions are honored. Set DisableRetries: true when the initial request must be the only attempt.

Client and NewsService are safe for concurrent use. Reuse a client instead of constructing one per request.

Cancellation

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

digest, err := client.News.Latest(ctx, nil)

Caller cancellation is returned as context.Canceled or context.DeadlineExceeded. The SDK's configured per-attempt timeout returns *newtqnia.TimeoutError.

Error handling

digest, err := client.News.Latest(ctx, nil)
if err != nil {
    var limited *newtqnia.RateLimitError
    var apiErr *newtqnia.APIError

    switch {
    case errors.As(err, &limited):
        log.Printf("retry after %s", limited.RetryAfter)
    case errors.As(err, &apiErr):
        log.Printf("status=%d request=%s code=%s", apiErr.StatusCode, apiErr.RequestID, apiErr.Code)
    default:
        log.Print(err)
    }
}

Specialized response errors are AuthenticationError, AuthorizationError, NotFoundError, ConflictError, RateLimitError, and ServerError. Configuration and parameter problems use ValidationError; exhausted transport failures use NetworkError.

Release and Go module publishing

Go modules are distributed from Git tags rather than uploaded to a package registry. For the first public release:

git tag -a v1.0.0 -m "NewTqnia Go SDK v1.0.0"
git push origin main v1.0.0
GOPROXY=https://proxy.golang.org go list -m github.com/newtqnia/newtqnia-go@v1.0.0

The module path, repository URL, package name, semantic version, license, documentation, and CI workflow are ready for discovery by the Go proxy and pkg.go.dev.

Development

go fmt ./...
go vet ./...
go test -race -cover ./...

See CONTRIBUTING.md, SECURITY.md, the changelog, and the MIT license.

Documentation

Overview

Package newtqnia provides the official Go client for the NewTqnia bilingual technology news API.

The public API is read-only and does not require authentication. Applications displaying API content must preserve returned article URLs and render the attribution included in each Digest.

Index

Examples

Constants

View Source
const (
	// Version is the semantic version of this SDK.
	Version = "1.0.0"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type APIError

type APIError struct {
	StatusCode int
	RequestID  string
	Code       string
	Message    string
	RetryAfter time.Duration
	Body       string
}

APIError is returned for a non-successful HTTP response.

func (*APIError) Error

func (e *APIError) Error() string

type Article

type Article struct {
	ID          int64     `json:"id"`
	Title       string    `json:"title"`
	Summary     string    `json:"summary"`
	Category    Category  `json:"category"`
	Image       string    `json:"image"`
	URL         string    `json:"url"`
	PublishedAt time.Time `json:"published_at"`
	ReadTime    int       `json:"read_time"`
}

Article is one localized NewTqnia article summary.

type Attribution

type Attribution struct {
	Text     string `json:"text"`
	URL      string `json:"url"`
	Required bool   `json:"required"`
}

Attribution contains the attribution that clients must display with API content.

type AuthenticationError

type AuthenticationError struct{ *APIError }

AuthenticationError reports an HTTP 401 response.

func (*AuthenticationError) Unwrap

func (e *AuthenticationError) Unwrap() error

type AuthorizationError

type AuthorizationError struct{ *APIError }

AuthorizationError reports an HTTP 403 response.

func (*AuthorizationError) Unwrap

func (e *AuthorizationError) Unwrap() error

type Category

type Category struct {
	Slug string `json:"slug"`
	Name string `json:"name"`
}

Category identifies an article category.

type Client

type Client struct {

	// News exposes localized news collection operations.
	News *NewsService
	// contains filtered or unexported fields
}

Client is a concurrency-safe NewTqnia API client.

Example
package main

import (
	"context"
	"fmt"
	"log"

	newtqnia "github.com/newtqnia/newtqnia-go"
)

func main() {
	client := newtqnia.New()
	digest, err := client.News.Latest(context.Background(), &newtqnia.NewsListParams{
		Locale: newtqnia.LocaleEnglish,
		Limit:  5,
	})
	if err != nil {
		log.Fatal(err)
	}
	for _, article := range digest.Articles {
		fmt.Println(article.Title, article.URL)
	}
}

func New

func New() *Client

New returns a client using production defaults. It is convenient for callers that do not need custom configuration.

func NewClient

func NewClient(config Config) (*Client, error)

NewClient constructs a client. The public endpoints require no API key.

type Collection

type Collection string

Collection identifies a news collection.

const (
	CollectionToday  Collection = "today"
	CollectionLatest Collection = "latest"
)

type Config

type Config struct {
	APIKey      string
	Application string
	Website     string
	BaseURL     string
	Timeout     time.Duration
	Retry       RetryConfig
	// DisableRetries makes the initial request the only attempt.
	DisableRetries bool
	HTTPClient     *http.Client
	UserAgent      string
	Headers        http.Header
}

Config configures a Client. Zero values use documented defaults.

type ConflictError

type ConflictError struct{ *APIError }

ConflictError reports an HTTP 409 response.

func (*ConflictError) Unwrap

func (e *ConflictError) Unwrap() error

type Digest

type Digest struct {
	APIVersion  string            `json:"api_version"`
	Collection  Collection        `json:"collection"`
	Date        string            `json:"date,omitempty"`
	Timezone    string            `json:"timezone"`
	Locale      Locale            `json:"locale"`
	Direction   string            `json:"direction"`
	Publisher   LinkLabel         `json:"publisher"`
	Attribution Attribution       `json:"attribution"`
	GeneratedAt time.Time         `json:"generated_at"`
	Articles    []Article         `json:"articles"`
	Links       map[string]string `json:"_links"`
}

Digest is a localized collection of news and its attribution metadata.

type LinkLabel

type LinkLabel struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}

LinkLabel contains a display label and its canonical URL.

type Locale

type Locale string

Locale is a supported response language.

const (
	LocaleEnglish Locale = "en"
	LocaleArabic  Locale = "ar"
)

type NetworkError

type NetworkError struct{ Err error }

NetworkError reports a transport failure after retries are exhausted.

func (*NetworkError) Error

func (e *NetworkError) Error() string

func (*NetworkError) Unwrap

func (e *NetworkError) Unwrap() error

type NewsListParams

type NewsListParams struct {
	// Locale defaults to LocaleEnglish.
	Locale Locale
	// Limit defaults to 10 and must be between 1 and 10 when set.
	Limit int
	// Category is an optional category slug.
	Category string
}

NewsListParams filters either public news collection.

type NewsService

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

NewsService provides the public news endpoints.

func (*NewsService) Latest

func (s *NewsService) Latest(ctx context.Context, params *NewsListParams) (*Digest, error)

Latest gets the latest published articles.

func (*NewsService) Today

func (s *NewsService) Today(ctx context.Context, params *NewsListParams) (*Digest, error)

Today gets articles published today using the Asia/Dubai day boundary.

type NotFoundError

type NotFoundError struct{ *APIError }

NotFoundError reports an HTTP 404 response.

func (*NotFoundError) Unwrap

func (e *NotFoundError) Unwrap() error

type RateLimitError

type RateLimitError struct{ *APIError }

RateLimitError reports an HTTP 429 response.

func (*RateLimitError) Unwrap

func (e *RateLimitError) Unwrap() error

type RetryConfig

type RetryConfig struct {
	MaxRetries  int
	InitialWait time.Duration
	MaxWait     time.Duration
}

RetryConfig controls retries after the initial request.

type ServerError

type ServerError struct{ *APIError }

ServerError reports an HTTP 5xx response.

func (*ServerError) Unwrap

func (e *ServerError) Unwrap() error

type TimeoutError

type TimeoutError struct {
	Duration time.Duration
	Err      error
}

TimeoutError reports expiry of the client request timeout.

func (*TimeoutError) Error

func (e *TimeoutError) Error() string

func (*TimeoutError) Unwrap

func (e *TimeoutError) Unwrap() error

type ValidationError

type ValidationError struct{ Message string }

ValidationError reports invalid client configuration or request parameters.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Directories

Path Synopsis
examples
arabic command
errors command
latest command

Jump to

Keyboard shortcuts

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