Table of Contents
- Introduction
- Prerequisites
- Setup
- Creating the Microservice
- Creating the Database
- Implementing the API Endpoints
- Testing the Microservice
- Conclusion
Introduction
In this tutorial, we will develop a Go-based microservice for ticket reservation. We will create an API that allows users to reserve, view, and cancel tickets. By the end of this tutorial, you will have a working microservice that can handle ticket reservations.
Prerequisites
Before getting started, make sure you have the following prerequisites:
- Basic understanding of Go programming language
- Go installed on your machine
- Familiarity with JSON and RESTful APIs
- MySQL or PostgreSQL database installed
Setup
To set up the project, follow these steps:
-
Create a new directory for your project.
-
Initialize a new Go module by running the following command in the project directory:
go mod init github.com/your-username/ticket-reservation
Creating the Microservice
The first step is to set up the basic structure of our microservice. We will create the main package, which will contain the entry point of our application.
-
Create a new file called
main.go
. -
Add the following code to import the necessary packages and define the main function: ```go package main
import ( "log" "net/http" ) func main() { // Start the HTTP server log.Fatal(http.ListenAndServe(":8080", nil)) } ```
Creating the Database
Next, let’s set up the database for ticket reservations. For this tutorial, we will use MySQL, but you can also use PostgreSQL or any other database of your choice.
-
Install the necessary Go packages to work with MySQL:
go get github.com/go-sql-driver/mysql
-
Open the
main.go
file and add the following code to establish a connection to the database: ```go package mainimport ( "database/sql" "log" "net/http" _ "github.com/go-sql-driver/mysql" ) var db *sql.DB func main() { // Connect to the database var err error db, err = sql.Open("mysql", "username:password@tcp(localhost:3306)/ticket_reservation") if err != nil { log.Fatal(err) } defer db.Close() // Start the HTTP server log.Fatal(http.ListenAndServe(":8080", nil)) } ```
-
Ensure you replace
username
andpassword
with your actual MySQL credentials.
Implementing the API Endpoints
Now, let’s implement the API endpoints for ticket reservation.
-
Create a new file called
handlers.go
and add the following code: ```go package mainimport ( "encoding/json" "log" "net/http" ) type Ticket struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email"` Status string `json:"status"` } func ReserveTicket(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") // Parse the request body var ticket Ticket err := json.NewDecoder(r.Body).Decode(&ticket) if err != nil { w.WriteHeader(http.StatusBadRequest) return } // Insert the ticket into the database _, err = db.Exec("INSERT INTO tickets (name, email, status) VALUES (?, ?, ?)", ticket.Name, ticket.Email, "reserved") if err != nil { log.Println(err) w.WriteHeader(http.StatusInternalServerError) return } w.WriteHeader(http.StatusCreated) } func CancelTicket(w http.ResponseWriter, r *http.Request) { // TODO: Implement cancel ticket logic } func GetTicket(w http.ResponseWriter, r *http.Request) { // TODO: Implement get ticket logic } ```
-
Open the
main.go
file and update themain
function to register the API endpoints: ```go package mainimport ( "database/sql" "log" "net/http" _ "github.com/go-sql-driver/mysql" ) var db *sql.DB func main() { // Connect to the database var err error db, err = sql.Open("mysql", "username:password@tcp(localhost:3306)/ticket_reservation") if err != nil { log.Fatal(err) } defer db.Close() // Register API endpoints http.HandleFunc("/tickets", ReserveTicket) http.HandleFunc("/tickets/{id}", CancelTicket) http.HandleFunc("/tickets/{id}", GetTicket) // Start the HTTP server log.Fatal(http.ListenAndServe(":8080", nil)) } ```
Testing the Microservice
Now, let’s test our microservice using an API testing tool like cURL or Postman.
-
Start the microservice by running the following command in the project directory:
go run main.go
-
Reserve a ticket by sending a
POST
request tohttp://localhost:8080/tickets
with the following payload:json { "name": "John Doe", "email": "[email protected]" }
-
Cancel a ticket by sending a
DELETE
request tohttp://localhost:8080/tickets/{id}
, replacing{id}
with the ID of the ticket you want to cancel. -
Get a ticket by sending a
GET
request tohttp://localhost:8080/tickets/{id}
, replacing{id}
with the ID of the ticket you want to retrieve.
Conclusion
Congratulations! You have successfully developed a Go-based microservice for ticket reservation. In this tutorial, we covered the basic setup, database connection, API endpoints, and testing of the microservice. You can now expand this microservice by adding more features and functionality based on your requirements.