<Back to Learning Page>

file struckture

/config
	- database.go //koneksi ke database (masukin uname and password 
								//template koneksinya dari github)
								//buat databasenya manual dari phpmyadmin baru add nama dbnya disini
								//table juga buat manual
								//on this project theres 2 table CATEGORY and PRODUCT
/entities
	- category.go //data struct kaya representasi tablenya kaya model klo di laravel
/models
	- categorymodel.go //query semua ada disini getAll,edit, create
/controllers
	- categorycontroller.go //atur request dan response dan arahin ke model
													//sama arahin ke pagenya
/views
	/category
		- index.html //page frontend

main.go //tempat semua dijalankan 
				//panggil connect DB
				//routing
				//jalanin server
  1. config / konfigurasi database

    1. install librarynya dulu dari github

      
      
    2. connect database

      package config
      
      import (
      	"database/sql"
      	"log"
      
      	_ "github.com/go-sql-driver/mysql"
      )
      
      var DB *sql.DB
      
      func ConnectDatabase() {
      	// Format: username:password@tcp(host:port)/dbname?parseTime=true
      	db, err := sql.Open("mysql", "root:@tcp(localhost:3306)/go_product?parseTime=true")
      	if err != nil {
      		panic(err)
      	}
      
      	log.Println("Database Connected")
      	DB = db
      }	 
      
  2. models

    1. struktur model

      func GetAll() []entities.Category {
      	rows, err := config.DB.Query("SELECT * FROM categories")
      	if err != nil {
      		panic(err)
      	}
      	defer rows.Close()
      
      	var categories []entities.Category
      
      	for rows.Next() {
      		var category entities.Category
      		// Scan data dari database ke struct
      		if err := rows.Scan(&category.Id, &category.Name, &category.CreatedAt, &category.UpdatedAt); err != nil {
      			panic(err)
      		}
      		categories = append(categories, category)
      	}
      
      	return categories
      }
      
      • func GetAll() = nama function
      • []entities.Category = bentuk output, entities itu nama package atau folder Category nama file yang udah diimport
      • selanjutnya bisa dipahami dari urutan codenya yh
      • pokok intinya ambil data dari database trus dimasukin struct itu
      • yang direturn variabel struct yang udah ada isinya
  3. controller

    1. structurt model

      func Index(w http.ResponseWriter, r *http.Request) {
      	categories := models.GetAll()
      	data := map[string]interface{}{
      		"categories": categories,
      	}
      
      	temp, _ := template.ParseFiles("views/category/index.html")
      	temp.Execute(w, data)
      }
      
      • func Index = nama function
      • (w httpResponseWriter, r *http.Request) = oke actually idk lemme search later
      • next masukin hasil models.getAll() ke variabel
      • trus i have no idea itu diapain lemme break down later
      • trus pokok kita tentuin page mana yang ditabpilin sama datanya
  4. routing

    1. structure

      	http.HandleFunc("/", controllers.Index) // Asumsi ada homecontroller
      	http.HandleFunc("/categories", controllers.Index)
      	http.HandleFunc("/categories/add", controllers.Add)
      
      • template :
      http.HandleFunc("pathurl",folder.functionName)
      
  5. show data in front end

    1. structure table

      						 <tbody>
                      {{ range .categories }} //for loop
                      <tr>
                          <td>{{ .Id }}</td>
                          <td>{{ .Name }}</td>
                          <td>
                              <a href="/categories/edit?id={{ .Id }}" class="btn btn-warning btn-sm">Edit</a>
                              <a href="/categories/delete?id={{ .Id }}" class="btn btn-danger btn-sm">Hapus</a>
                          </td>
                      </tr>
                      {{ end }}
                  </tbody>
      
      • for looping data = {{ range .categories}}
      • show field data = {{ .Id }}
      • button = href=”/edit?{{ .Id }}”
# Go Product Management App

A simple web application built with Go using MVC architecture to manage
Products and Categories.

This project was initially based on a tutorial, then broken down and refactored
to understand the flow of request handling, database interaction, and separation
of concerns in Go.

This project is purely for learning purposes.
During development, I wrote personal notes and breakdowns to better understand
each concept. The notes are available here:

📘 Learning Notes: <https://www.notion.so/GOLANG-CRUD-2e93a40147f78076a09dcd2a106083eb>

## 📁 Project Structure

config/ # Database connection
entities/ # Entity structs (table representation)
models/ # Database queries (CRUD)
controllers/ # Request & response handling
views/ # HTML templates
main.go # Application entry point

## 🚀 Features
- Category CRUD
- Product CRUD
- Server-side rendered HTML
- MySQL database
- MVC architecture

## 🛠 Tech Stack
- Go (net/http)
- MySQL
- HTML Templates
- database/sql
- go-sql-driver/mysql

## 🗄 Database Setup

Database and tables are created manually using phpMyAdmin.

### Tables
- `categories`
- `products`

## ⚙️ How to Run

1. Clone repository
```bash
git clone <https://github.com/maulinasabrina/go-product-app.git>

Setup environment variables

cp .env.example .env

Configure database credentials in .env

Run application

go run main.go

Open browser

<http://localhost:8080>

📌 Notes This project focuses on understanding MVC architecture in Go and handling CRUD operations without using a framework.