Go Client SDK

GoApp provides a convenient client SDK in the lib/goapp package. This library allows other Go applications to easily interact with the GoApp API without needing to handle HTTP requests and JSON marshaling manually.

Because this package is located in the lib/ directory (outside of internal/), it is a public-facing part of the project, intended for external consumption.

Installation

To use the client in your own Go project, install it using go get:

go get github.com/naughtygopher/goapp/lib/goapp

Usage

Using the client is straightforward. First, you import the package and create a new client instance, pointing it to the base URL of a running GoApp service.

1. Creating a Client

Instantiate the client with the base path of the GoApp API.

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/naughtygopher/goapp/lib/goapp"
)

func main() {
    // Create a new client pointing to the GoApp server
    client := goapp.NewClient("http://localhost:8080")

    // ... use the client
}

2. Creating a User

The CreateUser method takes a context.Context and a goapp.User struct pointer. It handles the POST /users API call.

func createUser(client *goapp.GoApp) (*goapp.User, error) {
    newUser := &goapp.User{
        FullName: "Alice Smith",
        Email:    "alice.smith@example.com",
    }

    createdUser, err := client.CreateUser(context.Background(), newUser)
    if err != nil {
        return nil, fmt.Errorf("failed to create user: %w", err)
    }

    fmt.Printf("Successfully created user with ID: %s\n", createdUser.ID)
    return createdUser, nil
}

3. Getting a User by Email

The UserByEmail method retrieves a user's details by making a GET /users/:email request.

func getUser(client *goapp.GoApp, email string) (*goapp.User, error) {
    user, err := client.UserByEmail(context.Background(), email)
    if err != nil {
        return nil, fmt.Errorf("failed to get user: %w", err)
    }

    fmt.Printf("Found user: %s (%s)\n", user.FullName, user.Email)
    return user, nil
}

Complete Example

Here is a full example demonstrating how to use the client.

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/naughtygopher/goapp/lib/goapp"
)

func main() {
    client := goapp.NewClient("http://localhost:8080")

    // Create a new user
    newUser := &goapp.User{
        FullName: "Alice Smith",
        Email:    "alice.smith@example.com",
    }

    createdUser, err := client.CreateUser(context.Background(), newUser)
    if err != nil {
        log.Fatalf("Error creating user: %v", err)
    }

    fmt.Printf("Created user: %+v\n", createdUser)

    // Get the user we just created
    fetchedUser, err := client.UserByEmail(context.Background(), "alice.smith@example.com")
    if err != nil {
        log.Fatalf("Error fetching user: %v", err)
    }

    fmt.Printf("Fetched user: %+v\n", fetchedUser)
}