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
torpedo init
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
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
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
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
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
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
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!

Golangisidealforperformance-criticalapplicationsandconcurrentprogramming,whilePythonexcelsindatascience,rapidprototyping,andversatility.1)Forhigh-performanceneeds,chooseGolangduetoitsefficiencyandconcurrencyfeatures.2)Fordata-drivenprojects,Pythonisp

Golang achieves efficient concurrency through goroutine and channel: 1.goroutine is a lightweight thread, started with the go keyword; 2.channel is used for secure communication between goroutines to avoid race conditions; 3. The usage example shows basic and advanced usage; 4. Common errors include deadlocks and data competition, which can be detected by gorun-race; 5. Performance optimization suggests reducing the use of channel, reasonably setting the number of goroutines, and using sync.Pool to manage memory.

Golang is more suitable for system programming and high concurrency applications, while Python is more suitable for data science and rapid development. 1) Golang is developed by Google, statically typing, emphasizing simplicity and efficiency, and is suitable for high concurrency scenarios. 2) Python is created by Guidovan Rossum, dynamically typed, concise syntax, wide application, suitable for beginners and data processing.

Golang is better than Python in terms of performance and scalability. 1) Golang's compilation-type characteristics and efficient concurrency model make it perform well in high concurrency scenarios. 2) Python, as an interpreted language, executes slowly, but can optimize performance through tools such as Cython.

Go language has unique advantages in concurrent programming, performance, learning curve, etc.: 1. Concurrent programming is realized through goroutine and channel, which is lightweight and efficient. 2. The compilation speed is fast and the operation performance is close to that of C language. 3. The grammar is concise, the learning curve is smooth, and the ecosystem is rich.

The main differences between Golang and Python are concurrency models, type systems, performance and execution speed. 1. Golang uses the CSP model, which is suitable for high concurrent tasks; Python relies on multi-threading and GIL, which is suitable for I/O-intensive tasks. 2. Golang is a static type, and Python is a dynamic type. 3. Golang compiled language execution speed is fast, and Python interpreted language development is fast.

Golang is usually slower than C, but Golang has more advantages in concurrent programming and development efficiency: 1) Golang's garbage collection and concurrency model makes it perform well in high concurrency scenarios; 2) C obtains higher performance through manual memory management and hardware optimization, but has higher development complexity.

Golang is widely used in cloud computing and DevOps, and its advantages lie in simplicity, efficiency and concurrent programming capabilities. 1) In cloud computing, Golang efficiently handles concurrent requests through goroutine and channel mechanisms. 2) In DevOps, Golang's fast compilation and cross-platform features make it the first choice for automation tools.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment