Build a message board using Golang, Gin and MySQL. It can do CRUD for management users.
- Download MySQL
- MySQL server 9.0.1 Innovation, Windows (x86, 64-bit), MSI Installer
- MySQL workbench 8.0.38, Windows (x86, 64-bit), MSI Installer
- Open MySQL workbench and build MySQL connections
- Create schema ( In MySQL, schema is equivalent to database )
- In this project, schema name is
go_database
( You can see insql/connect.yaml
)
- In this project, schema name is
.
├── controller
│ └── controller.go
├── model
│ └── model.go
├── repository
│ └── repository.go
├── router
│ └── router.go
└── sql
│ ├── connect.yaml
│ └── sql.go
├── go.mod
├── go.sum
└── main.go
Explain the individual functions and functions of the above folders:
controller
:Check logic of CRUD operation.model
:The data object.repository
:Functions of CRUD operation with database.router
:Set up website URL routing.sql
:The setting of database.
-
Following changes in Go 1.16, functionality in
ioutil
has been moved to theos
package. Therefore,ioutil.ReadFile
should be changed toos.ReadFile
-
If you encounter problems like:
{"message":"Error 1146 (42S02): Table 'go_database.message' doesn't exist"}
when you want to query message. Use theAutoMigrate
method to automatically create data tables. ( You can see insql/sql.go
)err = Connect.AutoMigrate(&model.Message{}) if err != nil { return fmt.Errorf("error running AutoMigrate: %w", err) }
go run main.go
CRUD operation instructions:
curl http://localhost:8081/api/v1/message
curl http://localhost:8081/api/v1/message/:id
curl -X POST http://localhost:8081/api/v1/message \
-H "Content-Type: application/x-www-form-urlencoded" \
-d 'User_Id=1&Content=Hi there'
curl -X PATCH http://localhost:8081/api/v1/message/3 \
-H "Content-Type: application/x-www-form-urlencoded" \
-d 'Content=Test three!!!'
curl -X DELETE http://localhost:8081/api/v1/message/:id