You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Serve runtime from assetserver if requested.
Add gin guide, fix asset server merge, add gin example
adding http.CloseNotifier and http.Flusher interface to assetserver.contentTypeSniffer, for Gin (and other framework) compatibility.
Copy file name to clipboardExpand all lines: docs/src/content/docs/guides/gin-services.mdx
+176-33
Original file line number
Diff line number
Diff line change
@@ -1,26 +1,49 @@
1
1
---
2
-
title: Using Gin in Services
2
+
title: Using Gin for Services
3
3
description: A guide to integrating the Gin web framework with Wails v3 Services
4
4
---
5
5
6
-
Wails v3 Services provide a powerful way to organize your application logic into reusable, modular components. By implementing the `http.Handler` interface in your services, you can mount them at specific routes in your application, allowing for a clean separation of concerns and more maintainable code.
6
+
# Using Gin for Services
7
7
8
-
Integrating Gin with Wails Services enables you to create modular, mountable HTTP APIs using Gin's powerful routing and middleware capabilities. You can organize your application into domain-specific services, mount multiple Gin-based services at different routes, leverage Gin's extensive feature set while maintaining the benefits of Wails Services, and seamlessly integrate with the Wails event system for real-time communication.
8
+
The Gin web framework is a popular choice for building HTTP services in Go. With Wails v3, you can easily integrate Gin-based services into your application, providing a powerful way to handle HTTP requests, implement RESTful APIs, and serve web content.
9
9
10
-
## Creating a Gin-based Service
10
+
This guide will walk you through creating a Gin-based service that can be mounted at a specific route in your Wails application. We'll build a complete example that demonstrates how to:
11
11
12
-
To create a Wails Service that uses Gin for HTTP handling, you need to implement both the Wails Service interface and the `http.Handler` interface. This combination allows your service to be managed by the Wails application lifecycle and handle HTTP requests. Let's walk through each step of the process:
12
+
1. Create a Gin-based service
13
+
2. Implement the Wails Service interface
14
+
3. Set up routes and middleware
15
+
4. Integrate with the Wails event system
16
+
5. Interact with the service from the frontend
13
17
14
-
### 1. Define Your Service Structure
18
+
##Prerequisites
15
19
16
-
First, create a new service structure that will hold your Gin router and any state your service needs. This structure serves as the foundation of your service, encapsulating both the HTTP handling capabilities and any business logic or data your service requires. The use of a mutex ensures thread-safe access to shared resources, which is essential for concurrent request handling.
20
+
Before you begin, make sure you have:
21
+
22
+
- Wails v3 installed
23
+
- Basic knowledge of Go and the Gin framework
24
+
- Familiarity with HTTP concepts and RESTful APIs
25
+
26
+
You'll need to add the Gin framework to your project:
27
+
28
+
```bash
29
+
go get github.com/gin-gonic/gin
30
+
```
31
+
32
+
## Creating a Gin-Based Service
33
+
34
+
Let's start by creating a Gin service that implements the Wails Service interface. Our service will manage a collection of users and provide API endpoints for retrieving and creating user records.
35
+
36
+
### 1. Define Your Data Models
37
+
38
+
First, define the data structures your service will work with:
17
39
18
40
```go
19
41
package services
20
42
21
43
import (
22
44
"context"
23
45
"net/http"
46
+
"strconv"
24
47
"sync"
25
48
"time"
26
49
@@ -36,6 +59,18 @@ type User struct {
36
59
CreatedAt time.Time`json:"createdAt"`
37
60
}
38
61
62
+
// EventData represents data sent in events
63
+
typeEventDatastruct {
64
+
Messagestring`json:"message"`
65
+
Timestampstring`json:"timestamp"`
66
+
}
67
+
```
68
+
69
+
### 2. Create Your Service Structure
70
+
71
+
Next, define the service structure that will hold your Gin router and any state your service needs to maintain:
72
+
73
+
```go
39
74
// GinService implements a Wails service that uses Gin for HTTP handling
Your service needs to implement the Wails Service interface with the required methods. The `ServiceName` method provides a human-readable identifier for your service. The `ServiceStartup` method is called when the service starts and gives you access to the Wails application instance, which you can use to register event handlers and access other Wails features. The `ServiceShutdown` method allows you to clean up resources when the service is shutting down.
111
+
Implement the required methodsfor the Wails Service interface:
77
112
78
113
```go
79
114
// ServiceName returns the name of the service
@@ -122,7 +157,7 @@ func (s *GinService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
122
157
123
158
### 4. Set Up Your Routes
124
159
125
-
Define your API routes in a separate method for better organization. This approach keeps your code clean and makes it easier to understand the structure of your API. The Gin router provides a fluent API for defining routes, including support for route groups, which help organize related endpoints.
160
+
Define your API routes in a separate method for better organisation. This approach keeps your code clean and makes it easier to understand the structure of your API. The Gin router provides a fluent API for defining routes, including support for route groups, which help organise related endpoints.
126
161
127
162
```go
128
163
// setupRoutes configures the API routes
@@ -191,6 +226,29 @@ func (s *GinService) setupRoutes() {
191
226
// Emit an event to notify about the new user
192
227
s.app.EmitEvent("user-created", newUser)
193
228
})
229
+
230
+
// Delete a user
231
+
users.DELETE("/:id", func(c *gin.Context) {
232
+
id, err:= strconv.Atoi(c.Param("id"))
233
+
if err != nil {
234
+
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid user ID"})
In this example, the Gin service is mounted at the `/api` route. This means that if your Gin router has an endpoint defined as `/info`, it will be accessible at `/api/info` in your application. This approach allows you to organize your API endpoints logically and avoid conflicts with other parts of your application.
302
+
In this example, the Gin service is mounted at the `/api` route. This means that if your Gin router has an endpoint defined as `/info`, it will be accessible at `/api/info` in your application. This approach allows you to organise your API endpoints logically and avoid conflicts with other parts of your application.
@@ -386,22 +545,6 @@ Here's an example of how to set up frontend integration:
386
545
</html>
387
546
```
388
547
389
-
## Best Practices
390
-
391
-
When using Gin with Wails Services, consider these best practices for creating maintainable and efficient applications:
392
-
393
-
- Modular Design: Organize your API endpoints into logical groups using Gin's router groups. This makes your code more readable and easier to maintain.
394
-
395
-
- Concurrency Safety: Use mutexes or other synchronization primitives when accessing shared state. This prevents race conditions and ensures data integrity.
396
-
397
-
- Error Handling: Implement consistent error handling across your API endpoints. This provides a better user experience and makes debugging easier.
398
-
399
-
- Logging: Use the Wails logger for consistent logging throughout your application. This helps with debugging and monitoring.
400
-
401
-
- Event-Driven Communication: Use the Wails event system for real-time updates and notifications. This creates a more responsive and interactive user experience.
402
-
403
-
- Security: Implement proper authentication and authorization for your API endpoints. This protects your application and user data.
404
-
405
548
## Closing Thoughts
406
549
407
550
Integrating the Gin web framework with Wails v3 Services provides a powerful and flexible approach to building modular, maintainable web applications. By leveraging Gin's routing and middleware capabilities alongside the Wails event system, you can create rich, interactive applications with clean separation of concerns.
0 commit comments