CRUD operations using GO language and Angular with proper code examples

 Creating a CRUD (Create, Read, Update, Delete) application with Go (Golang) for the backend and Angular for the frontend is a great way to understand both technologies. Below is a complete example of how to set up both parts.

1. Backend (Go with Gin Framework)

1.1 Set Up the Go Project

Create a directory for your project:

mkdir go-angular-crud cd go-angular-crud

Initialize a Go module:

go mod init go-angular-crud

Install Gin for routing:

go get github.com/gin-gonic/gin

You can also use other libraries like gorm for database management. For simplicity, we will use an in-memory data structure to store employee data.

1.2 Create the Model

Let's create an Employee struct that represents an employee.

models.go

package main type Employee struct { ID int `json:"id"` Name string `json:"name"` Position string `json:"position"` }

1.3 Create the Service to Manage Employees

employee_service.go

package main import "sync" type EmployeeService struct { employees map[int]Employee lock sync.Mutex } func NewEmployeeService() *EmployeeService { return &EmployeeService{ employees: make(map[int]Employee), } } // Create a new employee func (s *EmployeeService) CreateEmployee(employee Employee) Employee { s.lock.Lock() defer s.lock.Unlock() employee.ID = len(s.employees) + 1 s.employees[employee.ID] = employee return employee } // Get all employees func (s *EmployeeService) GetAllEmployees() []Employee { s.lock.Lock() defer s.lock.Unlock() employees := []Employee{} for _, employee := range s.employees { employees = append(employees, employee) } return employees } // Get a specific employee by ID func (s *EmployeeService) GetEmployeeByID(id int) (Employee, bool) { s.lock.Lock() defer s.lock.Unlock() employee, found := s.employees[id] return employee, found } // Update an existing employee func (s *EmployeeService) UpdateEmployee(id int, updated Employee) (Employee, bool) { s.lock.Lock() defer s.lock.Unlock() _, found := s.employees[id] if !found { return Employee{}, false } updated.ID = id s.employees[id] = updated return updated, true } // Delete an employee func (s *EmployeeService) DeleteEmployee(id int) bool { s.lock.Lock() defer s.lock.Unlock() _, found := s.employees[id] if !found { return false } delete(s.employees, id) return true }

1.4 Create the Controller (Router)

main.go

package main import ( "github.com/gin-gonic/gin" "net/http" ) var employeeService = NewEmployeeService() func main() { r := gin.Default() r.GET("/api/employees", GetAllEmployees) r.GET("/api/employees/:id", GetEmployeeByID) r.POST("/api/employees", CreateEmployee) r.PUT("/api/employees/:id", UpdateEmployee) r.DELETE("/api/employees/:id", DeleteEmployee) r.Run(":8080") } // Get all employees func GetAllEmployees(c *gin.Context) { employees := employeeService.GetAllEmployees() c.JSON(http.StatusOK, employees) } // Get a specific employee by ID func GetEmployeeByID(c *gin.Context) { id := c.Param("id") employee, found := employeeService.GetEmployeeByID(id) if !found { c.JSON(http.StatusNotFound, gin.H{"message": "Employee not found"}) return } c.JSON(http.StatusOK, employee) } // Create a new employee func CreateEmployee(c *gin.Context) { var employee Employee if err := c.BindJSON(&employee); err != nil { c.JSON(http.StatusBadRequest, gin.H{"message": "Invalid data"}) return } createdEmployee := employeeService.CreateEmployee(employee) c.JSON(http.StatusOK, createdEmployee) } // Update an employee func UpdateEmployee(c *gin.Context) { id := c.Param("id") var employee Employee if err := c.BindJSON(&employee); err != nil { c.JSON(http.StatusBadRequest, gin.H{"message": "Invalid data"}) return } updatedEmployee, found := employeeService.UpdateEmployee(id, employee) if !found { c.JSON(http.StatusNotFound, gin.H{"message": "Employee not found"}) return } c.JSON(http.StatusOK, updatedEmployee) } // Delete an employee func DeleteEmployee(c *gin.Context) { id := c.Param("id") if deleted := employeeService.DeleteEmployee(id); !deleted { c.JSON(http.StatusNotFound, gin.H{"message": "Employee not found"}) return } c.JSON(http.StatusOK, gin.H{"message": "Employee deleted"}) }

1.5 Run the Backend

Run the Go server:


go run main.go

The server will now be running at http://localhost:8080, and it will handle requests related to CRUD operations.

2. Frontend (Angular)

2.1 Create a New Angular Application

Create a new Angular project:

ng new angular-crud cd angular-crud

Install Angular Material and set up HTTP client:


ng add @angular/material

Generate a service to interact with the Go API:

ng generate service employee

2.2 Create Service to Communicate with the Backend

employee.service.ts

import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; interface Employee { id: number; name: string; position: string; } @Injectable({ providedIn: 'root' }) export class EmployeeService { private apiUrl = 'http://localhost:8080/api/employees'; // URL to Go backend constructor(private http: HttpClient) { } getEmployees(): Observable<Employee[]> { return this.http.get<Employee[]>(this.apiUrl); } getEmployeeById(id: number): Observable<Employee> { return this.http.get<Employee>(`${this.apiUrl}/${id}`); } createEmployee(employee: Employee): Observable<Employee> { return this.http.post<Employee>(this.apiUrl, employee); } updateEmployee(id: number, employee: Employee): Observable<Employee> { return this.http.put<Employee>(`${this.apiUrl}/${id}`, employee); } deleteEmployee(id: number): Observable<void> { return this.http.delete<void>(`${this.apiUrl}/${id}`); } }

2.3 Create the Component for Employee Management

employee.component.ts

import { Component, OnInit } from '@angular/core'; import { EmployeeService } from './employee.service'; @Component({ selector: 'app-employee', templateUrl: './employee.component.html', styleUrls: ['./employee.component.css'] }) export class EmployeeComponent implements OnInit { employees = []; employeeForm = { id: null, name: '', position: '' }; constructor(private employeeService: EmployeeService) { } ngOnInit(): void { this.getEmployees(); } getEmployees(): void { this.employeeService.getEmployees().subscribe(data => { this.employees = data; }); } createEmployee(): void { if (!this.employeeForm.id) { this.employeeService.createEmployee(this.employeeForm).subscribe(() => { this.getEmployees(); this.resetForm(); }); } else { this.employeeService.updateEmployee(this.employeeForm.id, this.employeeForm).subscribe(() => { this.getEmployees(); this.resetForm(); }); } } editEmployee(employee): void { this.employeeForm = { ...employee }; } deleteEmployee(id: number): void { this.employeeService.deleteEmployee(id).subscribe(() => { this.getEmployees(); }); } resetForm(): void { this.employeeForm = { id: null, name: '', position: '' }; } }

employee.component.html

<div> <h2>Employee List</h2> <table> <thead> <tr> <th>ID</th> <th>Name</th> <th>Position</th> <th>Actions</th> </tr> </thead> <tbody> <tr *ngFor="let employee of employees"> <td>{{ employee.id }}</td> <td>{{ employee.name }}</td> <td>{{ employee.position }}</td> <td> <button (click)="editEmployee(employee)">Edit</button> <button (click)="deleteEmployee(employee.id)">Delete</button> </td> </tr> </tbody> </table> <h3>{{ employeeForm.id ? 'Edit Employee' : 'Create Employee' }}</h3> <form (ngSubmit)="createEmployee()"> <input [(ngModel)]="employeeForm.name" name="name" placeholder="Name" required> <input [(ngModel)]="employeeForm.position" name="position" placeholder="Position" required> <button type="submit">{{ employeeForm.id ? 'Update' : 'Create' }}</button> </form> </div>

2.4 Add HttpClientModule to the App

Make sure you import HttpClientModule in your app.module.ts:

import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; import { EmployeeComponent } from './employee/employee.component'; @NgModule({ declarations: [ AppComponent, EmployeeComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

3. Run the Application

3.1 Start the Backend (Go)

Run the Go server:

go run main.go

3.2 Start the Frontend (Angular)

Start the Angular development server:

ng serve

The Angular app will now be available at http://localhost:4200, and it will interact with the Go backend on http://localhost:8080.

You now have a working CRUD application with Go and Angular!

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics