Welcome to our beginner-friendly guide on building a CRUD (Create, Read, Update, Delete) application using Golang and MySQL. In this tutorial, we'll walk through the process step by step, including setting up the environment, creating a professional folder structure, and writing code examples.
Before we begin, ensure you have the following installed on your system:
Once you have Golang and MySQL installed, let's set up our project environment.
mkdir go-crud-app
cd go-crud-app
go mod init github.com/your-username/go-crud-app
go get -u github.com/go-sql-driver/mysql
It's important to maintain a clean and professional folder structure for your project. Here's how you can structure your project folder:
go-crud-app/
├── README.md
├── cmd/
│ └── main.go
├── internal/
│ ├── config/
│ │ └── config.go
│ ├── handlers/
│ │ └── handlers.go
│ ├── models/
│ │ └── user.go
│ └── repository/
│ └── user_repository.go
└── go.mod
Now let's write the code for our CRUD application.
config/config.go
and define your MySQL connection details.
package config
const (
DBUser = "your_username"
DBPassword = "your_password"
DBName = "your_database_name"
)
models/user.go
to define our user model.
package models
type User struct {
ID int
Username string
Email string
}
repository/user_repository.go
.
package repository
import (
"database/sql"
"github.com/your-username/go-crud-app/internal/config"
"github.com/your-username/go-crud-app/internal/models"
)
func CreateUser(user *models.User) error {
// Implement SQL INSERT operation
}
func GetUserByID(id int) (*models.User, error) {
// Implement SQL SELECT operation
}
// Implement UpdateUser and DeleteUser functions similarly
handlers/handlers.go
.
package handlers
import (
"net/http"
"github.com/your-username/go-crud-app/internal/models"
)
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {
// Implement logic to create a new user
}
func GetUserHandler(w http.ResponseWriter, r *http.Request) {
// Implement logic to get a user by ID
}
// Implement UpdateUserHandler and DeleteUserHandler functions similarly
cmd/main.go
, set up HTTP routes and server initialization.
package main
import (
"net/http"
"github.com/your-username/go-crud-app/internal/handlers"
)
func main() {
// Define HTTP routes
http.HandleFunc("/users/create", handlers.CreateUserHandler)
http.HandleFunc("/users/{id}", handlers.GetUserHandler)
// Define other routes
// Start HTTP server
http.ListenAndServe(":8080", nil)
}
Congratulations! You've successfully created a CRUD application using Golang and MySQL. This tutorial covered setting up the environment, creating a professional folder structure, and writing code examples for each component of the application.
Feel free to expand upon this project by adding more features, implementing authentication, or improving error handling. Happy coding!
Источник: dev.to
Наш сайт является информационным посредником. Сообщить о нарушении авторских прав.
go mysql api backenddevelopment