Complete Backend API in Golang (JWT, MySQL & Tests)
Table of Contents
Introduction
In this tutorial, we will build a complete backend API in Go (Golang) using JWT authentication and MySQL as the database. This step-by-step guide will help you understand how to create a production-ready REST API, covering everything from server setup to user registration and authentication. By the end, you'll have the foundational knowledge to build your own APIs in Go.
Step 1: HTTP Server Setup
- Start by creating a new Go project.
- Initialize your Go module with the command:
go mod init your_project_name
- Import the necessary packages:
import ( "net/http" "github.com/gorilla/mux" )
- Create the HTTP server:
func main() { r := mux.NewRouter() http.Handle("/", r) http.ListenAndServe(":8000", nil) }
- Run your server using:
go run main.go
Step 2: User Service
- Define a struct to represent a User:
type User struct { ID uint `json:"id"` Username string `json:"username"` Password string `json:"password"` }
- Implement functionality to handle user operations such as registration and login.
Step 3: Database Connection and Environment Variables
- Set up a MySQL database and create a
.env
file for configuration. - Use the
godotenv
package to load environment variables:go get github.com/joho/godotenv
- Connect to the MySQL database:
import ( "database/sql" _ "github.com/go-sql-driver/mysql" ) func initDB() (*sql.DB, error) { return sql.Open("mysql", "user:password@/dbname") }
Step 4: User Registration
- Create a handler function for user registration:
func RegisterUser(w http.ResponseWriter, r *http.Request) { // Logic for user registration }
- Use the
POST
method to handle registration requests.
Step 5: Testing User Registration
- Use the
net/http/httptest
package to write tests for your registration endpoint:func TestRegisterUser(t *testing.T) { // Test logic here }
Step 6: Database Migrations
- Use a migration tool such as
golang-migrate
to manage your database schema. - Create migration files to set up user tables and other necessary structures.
Step 7: User Login
- Implement a login handler:
func LoginUser(w http.ResponseWriter, r *http.Request) { // Logic for user login }
- Validate user credentials and generate a JWT token upon successful login.
Step 8: JWT Authentication
- Install the JWT package:
go get github.com/dgrijalva/jwt-go
- Create functions to generate and validate JWT tokens:
func GenerateToken(user User) (string, error) { // Token generation logic } func ValidateToken(tokenString string) (*jwt.Token, error) { // Token validation logic }
Step 9: Products Service
- Define a struct for products and implement CRUD operations for the products service.
Step 10: Checkout Endpoint
- Create a checkout endpoint to handle product purchases and user transactions.
Step 11: Checking Logged-in Users
- Implement middleware to check if a user is logged in based on their JWT token.
Conclusion
In this tutorial, we have covered the essential steps to build a backend API in Go with JWT authentication and MySQL integration. You learned about setting up an HTTP server, creating user services, handling user registration and login, managing database migrations, and securing your API with JWT.
For next steps, consider exploring more advanced topics like authorization, error handling, and deploying your API to a cloud service. Happy coding!