client

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package client provides an HTTP client for interacting with Unimock APIs and mock endpoints.

Example
package main

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

	"github.com/bmcszk/unimock/pkg/client"
	"github.com/bmcszk/unimock/pkg/model"
)

func main() {
	// Create a new client
	clientInstance, err := client.NewClient("http://localhost:8080")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Create a context with timeout
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	// Create a new scenario
	scenario := model.Scenario{
		RequestPath: "GET /api/users",
		StatusCode:  200,
		ContentType: "application/json",
		Data:        `{"users": [{"id": "123", "name": "Test User"}]}`,
	}

	// Create the scenario
	createdScenario, err := clientInstance.CreateScenario(ctx, scenario)
	if err != nil {
		log.Fatalf("Failed to create scenario: %v", err)
	}

	fmt.Printf("Created scenario with UUID: %s\n", createdScenario.UUID)

	// Get all scenarios
	scenarios, err := clientInstance.ListScenarios(ctx)
	if err != nil {
		log.Fatalf("Failed to list scenarios: %v", err)
	}

	fmt.Printf("Found %d scenarios\n", len(scenarios))

	// Get a specific scenario
	retrievedScenario, err := clientInstance.GetScenario(ctx, createdScenario.UUID)
	if err != nil {
		log.Fatalf("Failed to get scenario: %v", err)
	}

	fmt.Printf("Retrieved scenario: %s %s\n", retrievedScenario.UUID, retrievedScenario.RequestPath)

	// Update the scenario
	updatedScenario := model.Scenario{
		UUID:        createdScenario.UUID,
		RequestPath: "GET /api/users",
		StatusCode:  201,
		ContentType: "application/json",
		Data:        `{"users": [{"id": "123", "name": "Updated User"}]}`,
	}

	_, err = clientInstance.UpdateScenario(ctx, createdScenario.UUID, updatedScenario)
	if err != nil {
		log.Fatalf("Failed to update scenario: %v", err)
	}

	fmt.Println("Updated scenario successfully")

	// Delete the scenario
	err = clientInstance.DeleteScenario(ctx, createdScenario.UUID)
	if err != nil {
		log.Fatalf("Failed to delete scenario: %v", err)
	}

	fmt.Println("Deleted scenario successfully")

	// Example using a context with cancellation
	ctx2, cancel2 := context.WithCancel(context.Background())
	go func() {
		time.Sleep(100 * time.Millisecond)
		cancel2() // Cancel after 100ms
	}()

	_, err = clientInstance.GetScenario(ctx2, "some-uuid")
	if err != nil {
		fmt.Println("Request was canceled as expected")
	}
}

Index

Examples

Constants

View Source
const (
	// DefaultBaseURL is the default base URL for the Unimock server
	DefaultBaseURL = "http://localhost:8080"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	// BaseURL is the base URL of the Unimock server
	BaseURL *url.URL

	// HTTPClient is the underlying HTTP client used to make requests
	HTTPClient *http.Client
}

Client is an HTTP client for interacting with the Unimock API

Example (Mixed_usage)

ExampleClient_mixed_usage demonstrates using both scenario management and HTTP requests

package main

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

	"github.com/bmcszk/unimock/pkg/client"
	"github.com/bmcszk/unimock/pkg/model"
)

func main() {
	// Create a client
	c, err := client.NewClient("http://localhost:8080")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

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

	// First, create a scenario for a specific endpoint
	scenario := model.Scenario{
		RequestPath: "GET /api/special/endpoint",
		StatusCode:  200,
		ContentType: "application/json",
		Data:        `{"message": "This is a predefined response"}`,
	}

	created, err := c.CreateScenario(ctx, scenario)
	if err != nil {
		log.Fatalf("Failed to create scenario: %v", err)
	}
	fmt.Printf("Created scenario: %s\n", created.UUID)

	// Now make a request to that endpoint and see the predefined response
	resp, err := c.Get(ctx, "/api/special/endpoint", nil)
	if err != nil {
		log.Fatalf("Failed to make request: %v", err)
	}
	fmt.Printf("Response: %s\n", string(resp.Body))

	// Test other endpoints with regular mock behavior
	userData := map[string]any{
		"id":   "user123",
		"name": "Regular User",
	}
	resp, err = c.PostJSON(ctx, "/api/users", nil, userData)
	if err != nil {
		log.Fatalf("Failed to create user: %v", err)
	}
	fmt.Printf("User created with status: %d\n", resp.StatusCode)

	// Verify the user was created
	resp, err = c.Get(ctx, "/api/users/user123", nil)
	if err != nil {
		log.Fatalf("Failed to get user: %v", err)
	}
	fmt.Printf("User retrieved with status: %d\n", resp.StatusCode)

	// Clean up
	err = c.DeleteScenario(ctx, created.UUID)
	if err != nil {
		log.Fatalf("Failed to delete scenario: %v", err)
	}

	_, err = c.Delete(ctx, "/api/users/user123", nil)
	if err != nil {
		log.Fatalf("Failed to delete user: %v", err)
	}
	fmt.Println("Cleanup completed")
}
Example (Universal_http_methods)

ExampleClient_universal_http_methods demonstrates using the client for universal HTTP requests

package main

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

	"github.com/bmcszk/unimock/pkg/client"
)

func main() {
	// Create a client
	c, err := client.NewClient("http://localhost:8080")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

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

	// Make a GET request
	resp, err := c.Get(ctx, "/api/users/123", map[string]string{
		"Authorization": "Bearer token",
	})
	if err != nil {
		log.Fatalf("GET request failed: %v", err)
	}
	fmt.Printf("GET Status: %d\n", resp.StatusCode)

	// Create a user with PostJSON
	userData := map[string]any{
		"id":   "123",
		"name": "John Doe",
	}
	resp, err = c.PostJSON(ctx, "/api/users", nil, userData)
	if err != nil {
		log.Fatalf("POST request failed: %v", err)
	}
	fmt.Printf("POST Status: %d\n", resp.StatusCode)

	// Check if resource exists with HEAD
	resp, err = c.Head(ctx, "/api/users/123", nil)
	if err != nil {
		log.Fatalf("HEAD request failed: %v", err)
	}
	fmt.Printf("HEAD Status: %d\n", resp.StatusCode)

	// Update with PutJSON
	updatedData := map[string]any{
		"id":   "123",
		"name": "Jane Doe",
	}
	resp, err = c.PutJSON(ctx, "/api/users/123", nil, updatedData)
	if err != nil {
		log.Fatalf("PUT request failed: %v", err)
	}
	fmt.Printf("PUT Status: %d\n", resp.StatusCode)

	// Delete the user
	resp, err = c.Delete(ctx, "/api/users/123", nil)
	if err != nil {
		log.Fatalf("DELETE request failed: %v", err)
	}
	fmt.Printf("DELETE Status: %d\n", resp.StatusCode)
}

func NewClient

func NewClient(baseURL string) (*Client, error)

NewClient creates a new client with the given base URL

func (*Client) CreateScenario

func (c *Client) CreateScenario(ctx context.Context, scenario model.Scenario) (model.Scenario, error)

CreateScenario creates a new scenario

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, urlPath string, headers map[string]string) (*Response, error)

Delete performs a DELETE request to the specified path

func (*Client) DeleteScenario

func (c *Client) DeleteScenario(ctx context.Context, uuid string) error

DeleteScenario deletes a scenario by UUID

func (*Client) Get

func (c *Client) Get(ctx context.Context, urlPath string, headers map[string]string) (*Response, error)

Get performs a GET request to the specified path

func (*Client) GetScenario

func (c *Client) GetScenario(ctx context.Context, uuid string) (model.Scenario, error)

GetScenario gets a scenario by UUID

func (*Client) Head

func (c *Client) Head(ctx context.Context, urlPath string, headers map[string]string) (*Response, error)

Head performs a HEAD request to the specified path

func (*Client) HealthCheck

func (c *Client) HealthCheck(ctx context.Context) (*Response, error)

HealthCheck performs a health check on the Unimock server

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/bmcszk/unimock/pkg/client"
)

func main() {
	// Create client
	c, err := client.NewClient("http://localhost:8080")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	ctx := context.Background()

	// Check server health
	resp, err := c.HealthCheck(ctx)
	if err != nil {
		log.Fatalf("Health check failed: %v", err)
	}

	fmt.Printf("Health check status: %d\n", resp.StatusCode)
	if resp.StatusCode == 200 {
		fmt.Println("Server is healthy")
	}
}

func (*Client) ListScenarios

func (c *Client) ListScenarios(ctx context.Context) ([]model.Scenario, error)

ListScenarios gets all scenarios

func (*Client) Options

func (c *Client) Options(ctx context.Context, urlPath string, headers map[string]string) (*Response, error)

Options performs an OPTIONS request to the specified path

func (*Client) Patch

func (c *Client) Patch(ctx context.Context, urlPath string, headers map[string]string, body []byte) (*Response, error)

Patch performs a PATCH request to the specified path with the given body

func (*Client) PatchJSON

func (c *Client) PatchJSON(
	ctx context.Context,
	urlPath string,
	headers map[string]string,
	data any,
) (*Response, error)

PatchJSON performs a PATCH request with JSON content

func (*Client) Post

func (c *Client) Post(ctx context.Context, urlPath string, headers map[string]string, body []byte) (*Response, error)

Post performs a POST request to the specified path with the given body

func (*Client) PostJSON

func (c *Client) PostJSON(ctx context.Context, urlPath string, headers map[string]string, data any) (*Response, error)

PostJSON performs a POST request with JSON content

func (*Client) Put

func (c *Client) Put(ctx context.Context, urlPath string, headers map[string]string, body []byte) (*Response, error)

Put performs a PUT request to the specified path with the given body

func (*Client) PutJSON

func (c *Client) PutJSON(ctx context.Context, urlPath string, headers map[string]string, data any) (*Response, error)

PutJSON performs a PUT request with JSON content

func (*Client) UpdateScenario

func (c *Client) UpdateScenario(ctx context.Context, uuid string, scenario model.Scenario) (model.Scenario, error)

UpdateScenario updates an existing scenario

type Response

type Response struct {
	// StatusCode is the HTTP status code (200, 404, etc.)
	StatusCode int

	// Headers contains the response headers
	Headers http.Header

	// Body contains the response body content
	Body []byte
}

Response represents an HTTP response from the server

Jump to

Keyboard shortcuts

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