Home Backend Development Golang Creating Your First Project with Torpedo: A Step-by-Step Guide

Creating Your First Project with Torpedo: A Step-by-Step Guide

Nov 18, 2024 am 09:06 AM

Creating Your First Project with Torpedo: A Step-by-Step Guide

When building applications in Golang, adhering to the principles of Hexagonal Architecture can ensure clean, modular, and maintainable code. With Torpedo, you can easily implement this architecture while speeding up your development process. In this guide, we’ll walk through how to create your first project with Torpedo, from installation to generating entities and use cases.

This post is a summary of the documented quick start guide

1. Getting Started with Torpedo

Before we dive into creating a project, make sure you have Go installed on your system. Then, install Torpedo following the instructions at installation guide

This CLI tool will handle project generation, entity creation, and use case scaffolding for you. Once installed, you’re ready to create your first project.

2. Setting Up Your First Project

Lets begging with our first application built with Torpedo!. We will be building a fly reservation app called Booking Fly.

With Torpedo installed, creating a new project is as simple as running:

mkdir booking-fly && cd booking-fly
Copy after login
Copy after login
torpedo init
Copy after login
Copy after login

This command will generate the folder .torpedo where you should defines your entities and use cases. More info about this folder can be found at .torpedo dir struct

3. Defining Your First Entity

Next, you’ll want to define your domain entities. Entities are the core objects in your application’s business logic, representing things like User, Product, or Order.

To define your first entity, create a YAML file under the .torpedo/entities directory. For example, let’s create a simple User entity:

.torpedo/entities/user.yaml

version: torpedo.darksub.io/v1.0
kind: entity
spec:
    name: "user"
    plural: "users" 
    description: "The frequent flyer user"
    doc: |
        The user entity represents a system user but also a frequent flyer. 
        This entity is only for the example purpose.
    schema:
        reserved:
            id:
                type: ulid 

        fields:
          - name: name
            type: string
            description: "The user full name"

          - name: email
            type: string
            description: "The user contact email"

          - name: password # it is not recommended to save passwords, this is an example only
            type: string
            encrypted: true
            description: "The user system password"

          - name: plan
            type: string
            description: "The user membership plan"
            validate:
              list:
                values:
                  - GOLD
                  - SILVER
                  - BRONZE

          - name: miles
            type: integer
            description: "The accumulated flyer miles"

    relationships:
        - name: trips
          type: $rel
          ref: ".torpedo/entities/trip.yaml"
          cardinality: hasMany
          load:
            type: nested
            metadata:
                maxItems: 100

    adapters:
        input:
            - type: http

        output:
          - type: memory 

Copy after login
Copy after login

Additionally the Trip entity is required, so, let’s create a Trip entity:

.torpedo/entities/trip.yaml

version: torpedo.darksub.io/v1.0
kind: entity
spec:
    name: trip
    plural: trips
    description: "The user fly trip reservations"
    doc: |
        The trip entity handles all data related with the frequent flyer trip
    schema:
        reserved:
            id:
                type: ulid

        fields:
          - name: departure
            type: string
            description: "The trip departure airport"

          - name: arrival
            type: string
            description: "The trip arrival airport"

          - name: miles
            type: integer
            description: "The trip miles"

          - name: from
            type: date
            description: "The trip from date"

          - name: to
            type: date
            description: "The trip to date"

    adapters:
        input:
            - type: http

        output:
            - type: memory

Copy after login
Copy after login

Torpedo will generate the Go code for the User and Trip entities along with its corresponding CRUD operations, including the repository interfaces and any necessary database handling code.

4. Creating Use Cases

Once your entities are in place, it’s time to define how they’ll interact with the application’s workflows using use cases. Use cases encapsulate the business rules and processes that act upon your entities.

Create a YAML file under the .torpedo/use_cases directory to define your use case. Here’s an example of a simple use case for booking a fly:

.torpedo/use_cases/booking_fly.yaml

mkdir booking-fly && cd booking-fly
Copy after login
Copy after login

This definition tells Torpedo to create the skeleton code to put your custom logic for processing a fly reservation given a Trip and a User.

Torpedo will scaffold the complete use case, including interactions with your entities.

After complete the next step (#5) please read the quick start guide to learn about how to code your logic within the generated skeleton use case at Use Cases

5. Wiring It All Together

Once you’ve defined your entities and use cases, Torpedo ensures that the wiring between these components follows Hexagonal Architecture principles. The use cases will interact with the entities through the service interfaces, while your adapters (such as databases or APIs) handle persistence and external communication.

Now it's time to write your app specification to put all together!. The application definition is the most important file because here is described your app. The following example shows how to define the Booking Fly app:

.torpedo/app.yaml

torpedo init
Copy after login
Copy after login

To generate the application code (entities, use cases and more) run the command:

version: torpedo.darksub.io/v1.0
kind: entity
spec:
    name: "user"
    plural: "users" 
    description: "The frequent flyer user"
    doc: |
        The user entity represents a system user but also a frequent flyer. 
        This entity is only for the example purpose.
    schema:
        reserved:
            id:
                type: ulid 

        fields:
          - name: name
            type: string
            description: "The user full name"

          - name: email
            type: string
            description: "The user contact email"

          - name: password # it is not recommended to save passwords, this is an example only
            type: string
            encrypted: true
            description: "The user system password"

          - name: plan
            type: string
            description: "The user membership plan"
            validate:
              list:
                values:
                  - GOLD
                  - SILVER
                  - BRONZE

          - name: miles
            type: integer
            description: "The accumulated flyer miles"

    relationships:
        - name: trips
          type: $rel
          ref: ".torpedo/entities/trip.yaml"
          cardinality: hasMany
          load:
            type: nested
            metadata:
                maxItems: 100

    adapters:
        input:
            - type: http

        output:
          - type: memory 

Copy after login
Copy after login

This command will generate a project scaffold, setting up the directory structure based on the Hexagonal Architecture. The project will include core folders for entities, use cases, and adapters. It ensures that your business logic and infrastructure remain decoupled from the get-go.

You can now extend your project by adding more entities, use cases, and even custom adapters. Torpedo’s structure allows you to keep your code clean and modular, making it easy to scale your application as it grows.

Also take a look at how to code your own logic withing generated Use Case code.

6. Running Your Application

After setting up entities and use cases, you’re ready to run your application. Torpedo includes a lightweight server, based on Gin Gonic project, that you can run for testing and development. Simply use:

Don't forget to run go mod tidy before to update dependencies!

version: torpedo.darksub.io/v1.0
kind: entity
spec:
    name: trip
    plural: trips
    description: "The user fly trip reservations"
    doc: |
        The trip entity handles all data related with the frequent flyer trip
    schema:
        reserved:
            id:
                type: ulid

        fields:
          - name: departure
            type: string
            description: "The trip departure airport"

          - name: arrival
            type: string
            description: "The trip arrival airport"

          - name: miles
            type: integer
            description: "The trip miles"

          - name: from
            type: date
            description: "The trip from date"

          - name: to
            type: date
            description: "The trip to date"

    adapters:
        input:
            - type: http

        output:
            - type: memory

Copy after login
Copy after login

You can now interact with your application’s API, running the CRUD operations and use cases you’ve defined.

7. What’s Next?

Torpedo makes it easy to generate clean, structured Go code with Hexagonal Architecture. But this is just the beginning! You can continue to explore Torpedo’s features by adding more complex workflows, integrating external services, and customizing the framework to suit your needs.

Stay tuned for more advanced features coming soon to Torpedo, and feel free to share your feedback as you explore what’s possible!


Conclusion

Creating your first project with Torpedo is simple and fast. By leveraging the power of entity schemas and use case definitions in YAML, you can quickly scaffold a robust Golang application while maintaining clean architectural principles. Now it's time to dive in and start building! Let us know what you think and how Torpedo can help your future projects.

The above is the detailed content of Creating Your First Project with Torpedo: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Transforming from front-end to back-end development, is it more promising to learn Java or Golang? Apr 02, 2025 am 09:12 AM

Backend learning path: The exploration journey from front-end to back-end As a back-end beginner who transforms from front-end development, you already have the foundation of nodejs,...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

How to specify the database associated with the model in Beego ORM? How to specify the database associated with the model in Beego ORM? Apr 02, 2025 pm 03:54 PM

Under the BeegoORM framework, how to specify the database associated with the model? Many Beego projects require multiple databases to be operated simultaneously. When using Beego...

How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

See all articles