Building a Photo Sharing App with Go and Angular

Table of Contents

  1. Introduction
  2. Prerequisites
  3. Setup
  4. Building the Backend
  5. Building the Frontend
  6. Conclusion

Introduction

In this tutorial, we will learn how to build a photo sharing app using the Go programming language for the backend and Angular for the frontend. By the end of this tutorial, you will have a fully functional web application where users can upload, view, and share photos.

Prerequisites

Before you begin this tutorial, make sure you have the following:

  • Basic knowledge of Go programming language
  • Basic knowledge of Angular framework
  • Go installed on your machine
  • Node.js and Angular CLI installed on your machine

Setup

To get started, let’s set up the project structure and dependencies.

  1. Create a new directory for your project: $ mkdir photo-sharing-app $ cd photo-sharing-app

  2. Initialize a Go module: $ go mod init github.com/username/photo-sharing-app

  3. Create a main.go file and add the following code to start a basic Go web server: ```go package main

    import (
    	"fmt"
    	"log"
    	"net/http"
    )
    
    func mainHandler(w http.ResponseWriter, r *http.Request) {
    	fmt.Fprintln(w, "Welcome to the Photo Sharing App!")
    }
    
    func main() {
    	http.HandleFunc("/", mainHandler)
    
    	log.Println("Server started on port 8080")
    	log.Fatal(http.ListenAndServe(":8080", nil))
    }
    ```
    
  4. Install the necessary Go packages: $ go get github.com/gorilla/mux

  5. Create an index.html file in the root directory of your project and add a basic HTML structure: html <!DOCTYPE html> <html> <head> <title>Photo Sharing App</title> </head> <body> <h1>Welcome to the Photo Sharing App!</h1> </body> </html>

  6. Initialize an Angular project inside the web directory: $ cd web $ ng new frontend

  7. Update the src/app/app.component.html file with the following HTML code: html <h1>Photo Sharing App</h1> <router-outlet></router-outlet>

  8. Start the Angular development server: $ ng serve

    Now that we have the basic project structure and setup ready, let’s move on to building the backend and frontend components.

Building the Backend

  1. Import the necessary Go packages at the top of your main.go file: ```go package main

    import (
    	"fmt"
    	"html/template"
    	"log"
    	"net/http"
    
    	"github.com/gorilla/mux"
    )
    ```
    
  2. Create a handlers.go file in the root directory and define the required handler functions: ```go package main

    import (
    	"fmt"
    	"html/template"
    	"log"
    	"net/http"
    )
    
    func homeHandler(w http.ResponseWriter, r *http.Request) {
    	tmpl := template.Must(template.ParseFiles("index.html"))
    
    	err := tmpl.Execute(w, nil)
    	if err != nil {
    		log.Println(err)
    		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
    	}
    }
    
    func uploadHandler(w http.ResponseWriter, r *http.Request) {
    	if r.Method == "POST" {
    		// Handle photo upload logic here
    		fmt.Fprintln(w, "Photo uploaded successfully!")
    		return
    	}
    
    	// Render the upload form
    	tmpl := template.Must(template.ParseFiles("upload.html"))
    
    	err := tmpl.Execute(w, nil)
    	if err != nil {
    		log.Println(err)
    		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
    	}
    }
    
    func main() {
    	r := mux.NewRouter()
    
    	r.HandleFunc("/", homeHandler)
    	r.HandleFunc("/upload", uploadHandler)
    
    	log.Println("Server started on port 8080")
    	log.Fatal(http.ListenAndServe(":8080", r))
    }
    ```
    
  3. Create an upload.html file in the root directory and add a form for uploading photos: html <!DOCTYPE html> <html> <head> <title>Photo Sharing App - Upload</title> </head> <body> <h1>Upload a Photo</h1> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="photo"> <input type="submit" value="Upload"> </form> </body> </html>

  4. Update the mainHandler function in your main.go file to redirect to the home page: go func mainHandler(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, "/home", http.StatusFound) }

    Now, if you run the Go server with go run main.go, you should be able to access the home page and upload a photo through the /upload route.

Building the Frontend

  1. Update the src/app/app.component.html file in your Angular project to include a link to the upload page: html <h1>Photo Sharing App</h1> <a routerLink="/upload">Upload a Photo</a> <hr> <router-outlet></router-outlet>

  2. Generate a new component for the upload page: $ cd web/src/app $ ng generate component upload

  3. Update the upload.component.html file with the following code: html <h2>Upload a Photo</h2> <form> <input type="file" name="photo"> <button type="submit">Upload</button> </form>

  4. Add a route for the upload page in the app-routing.module.ts file: ```typescript import { NgModule } from ‘@angular/core’; import { Routes, RouterModule } from ‘@angular/router’; import { UploadComponent } from ‘./upload/upload.component’;

    const routes: Routes = [
        { path: 'upload', component: UploadComponent }
    ];
    
    @NgModule({
        imports: [RouterModule.forRoot(routes)],
        exports: [RouterModule]
    })
    export class AppRoutingModule { }
    ```
    
  5. Update the app.module.ts file to import and declare the UploadComponent: ```typescript import { NgModule } from ‘@angular/core’; import { BrowserModule } from ‘@angular/platform-browser’; import { AppRoutingModule } from ‘./app-routing.module’; import { AppComponent } from ‘./app.component’; import { UploadComponent } from ‘./upload/upload.component’;

    @NgModule({
        declarations: [
            AppComponent,
            UploadComponent
        ],
        imports: [
            BrowserModule,
            AppRoutingModule
        ],
        providers: [],
        bootstrap: [AppComponent]
    })
    export class AppModule { }
    ```
    

    Now, if you run the Angular development server with ng serve, you should be able to navigate to the upload page and see the photo upload form.

Conclusion

Congratulations! You have successfully built a photo sharing app using Go for the backend and Angular for the frontend. You learned how to set up the project, handle photo uploads, and create the necessary routes and components in both Go and Angular.

Feel free to explore and expand upon this app by adding features like user authentication, photo viewing, and social sharing functionality. Happy coding!