goLang tutorials from basic to advance with CRUD examples using angular in frontend

 Creating a GoLang (Go) application that integrates with a frontend built using Angular for a complete CRUD (Create, Read, Update, Delete) example can be a rewarding project to understand both backend and frontend technologies. Here’s a structured tutorial that takes you from basic Go concepts to advanced topics, using Go for the backend and Angular for the frontend.

Part 1: Set Up Go Backend

  1. Install Go

    • Download and install Go from the official website: Go Downloads.
  2. Create a Go Project

    • Create a directory for your project:
      bash
      mkdir go-angular-crud cd go-angular-crud
  3. Go CRUD Operations (Backend)

    Install Dependencies

    • Install gorilla/mux for routing:
      bash
      go get -u github.com/gorilla/mux

    Create the Main Go Application (main.go)

    go
    package main import ( "encoding/json" "fmt" "log" "net/http" "github.com/gorilla/mux" ) // Struct to represent a task type Task struct { ID string `json:"id"` Title string `json:"title"` Content string `json:"content"` } // Sample tasks var tasks = []Task{ {ID: "1", Title: "First Task", Content: "Content of the first task"}, {ID: "2", Title: "Second Task", Content: "Content of the second task"}, } // Get all tasks func getTasks(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(tasks) } // Get a single task func getTask(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) for _, task := range tasks { if task.ID == params["id"] { w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(task) return } } http.Error(w, "Task not found", http.StatusNotFound) } // Create a new task func createTask(w http.ResponseWriter, r *http.Request) { var task Task _ = json.NewDecoder(r.Body).Decode(&task) task.ID = fmt.Sprintf("%d", len(tasks)+1) tasks = append(tasks, task) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(task) } // Update an existing task func updateTask(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) for index, task := range tasks { if task.ID == params["id"] { _ = json.NewDecoder(r.Body).Decode(&task) tasks[index] = task w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(task) return } } http.Error(w, "Task not found", http.StatusNotFound) } // Delete a task func deleteTask(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) for index, task := range tasks { if task.ID == params["id"] { tasks = append(tasks[:index], tasks[index+1:]...) w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(tasks) return } } http.Error(w, "Task not found", http.StatusNotFound) } func main() { r := mux.NewRouter() // Routes r.HandleFunc("/tasks", getTasks).Methods("GET") r.HandleFunc("/tasks/{id}", getTask).Methods("GET") r.HandleFunc("/tasks", createTask).Methods("POST") r.HandleFunc("/tasks/{id}", updateTask).Methods("PUT") r.HandleFunc("/tasks/{id}", deleteTask).Methods("DELETE") log.Fatal(http.ListenAndServe(":8000", r)) }
  4. Run the Go Server

    bash
    go run main.go

    Your Go backend will now be running at http://localhost:8000.


Part 2: Set Up Angular Frontend

  1. Install Node.js and Angular CLI

    • Install Node.js from Node.js.
    • Install Angular CLI:
      bash
      npm install -g @angular/cli
  2. Create Angular Project

    bash
    ng new angular-crud-app cd angular-crud-app
  3. Install HTTP Client Module Angular uses the HttpClient module to make HTTP requests to the backend. Ensure you have it by importing it in your app.module.ts:

    typescript
    import { HttpClientModule } from '@angular/common/http'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppComponent } from './app.component'; @NgModule({ declarations: [AppComponent], imports: [BrowserModule, HttpClientModule], providers: [], bootstrap: [AppComponent] }) export class AppModule {}
  4. Create Angular Services for CRUD Operations

    Create a service to handle HTTP requests for CRUD operations. Run the following command to generate the service:

    bash
    ng generate service task

    task.service.ts

    typescript
    import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; interface Task { id: string; title: string; content: string; } @Injectable({ providedIn: 'root', }) export class TaskService { private apiUrl = 'http://localhost:8000/tasks'; constructor(private http: HttpClient) {} getTasks(): Observable<Task[]> { return this.http.get<Task[]>(this.apiUrl); } getTask(id: string): Observable<Task> { return this.http.get<Task>(`${this.apiUrl}/${id}`); } createTask(task: Task): Observable<Task> { return this.http.post<Task>(this.apiUrl, task); } updateTask(id: string, task: Task): Observable<Task> { return this.http.put<Task>(`${this.apiUrl}/${id}`, task); } deleteTask(id: string): Observable<Task[]> { return this.http.delete<Task[]>(`${this.apiUrl}/${id}`); } }
  5. Create Angular Components for CRUD Operations

    Generate a component for tasks:

    bash
    ng generate component task-list ng generate component task-form

    task-list.component.ts

    typescript
    import { Component, OnInit } from '@angular/core'; import { TaskService } from '../task.service'; @Component({ selector: 'app-task-list', templateUrl: './task-list.component.html', styleUrls: ['./task-list.component.css'] }) export class TaskListComponent implements OnInit { tasks = []; constructor(private taskService: TaskService) {} ngOnInit(): void { this.loadTasks(); } loadTasks() { this.taskService.getTasks().subscribe((data) => { this.tasks = data; }); } deleteTask(id: string) { this.taskService.deleteTask(id).subscribe(() => { this.loadTasks(); }); } }

    task-list.component.html

    html
    <div *ngFor="let task of tasks"> <p>{{ task.title }} - {{ task.content }}</p> <button (click)="deleteTask(task.id)">Delete</button> </div>
  6. Update Task Form for Add/Edit Tasks

    task-form.component.ts

    typescript
    import { Component, OnInit } from '@angular/core'; import { TaskService } from '../task.service'; import { ActivatedRoute, Router } from '@angular/router'; @Component({ selector: 'app-task-form', templateUrl: './task-form.component.html', styleUrls: ['./task-form.component.css'] }) export class TaskFormComponent implements OnInit { task = { id: '', title: '', content: '' }; constructor( private taskService: TaskService, private route: ActivatedRoute, private router: Router ) {} ngOnInit(): void { const id = this.route.snapshot.paramMap.get('id'); if (id) { this.taskService.getTask(id).subscribe((data) => { this.task = data; }); } } saveTask() { if (this.task.id) { this.taskService.updateTask(this.task.id, this.task).subscribe(() => { this.router.navigate(['/']); }); } else { this.taskService.createTask(this.task).subscribe(() => { this.router.navigate(['/']); }); } } }

    task-form.component.html

    html
    <form (ngSubmit)="saveTask()"> <label for="title">Title</label> <input type="text" [(ngModel)]="task.title" name="title" required /> <label for="content">Content</label> <input type="text" [(ngModel)]="task.content" name="content" required /> <button type="submit">Save</button> </form>

Part 3: Connect Frontend with Backend

  1. Start the Angular Development Server

    bash
    ng serve

    Your Angular app will be running at http://localhost:4200.

  2. Test the Application

    • Open http://localhost:4200 and test all CRUD functionalities:
      • View tasks (GET).
      • Add a task (POST).
      • Edit a task (PUT).
      • Delete a task (DELETE).

Part 4: Advanced Topics (Optional)

  1. Authentication and Authorization: Implement JWT-based authentication to secure your API.
  2. Database Integration: Replace the in-memory data structure with a database like MySQL or MongoDB.
  3. State Management: Use Angular's ngrx or ngx-store for state management for complex data flows.

This tutorial should guide you through building a full-stack CRUD application with Go as the backend and Angular as the frontend.

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