Go 语言是一种高性能的编程语言,适用于构建高并发、分布式和微服务架构的应用程序
package main
import (
"fmt"
)
type Task func() error
type Workflow struct {
tasks []Task
}
func NewWorkflow() *Workflow {
return &Workflow{
tasks: make([]Task, 0),
}
}
func (w *Workflow) AddTask(task Task) {
w.tasks = append(w.tasks, task)
}
func (w *Workflow) Run() error {
for _, task := range w.tasks {
if err := task(); err != nil {
return err
}
}
return nil
}
func main() {
workflow := NewWorkflow()
workflow.AddTask(func() error {
fmt.Println("Task 1: Initialize database connection")
return nil
})
workflow.AddTask(func() error {
fmt.Println("Task 2: Create tables")
return nil
})
workflow.AddTask(func() error {
fmt.Println("Task 3: Insert data")
return nil
})
workflow.AddTask(func() error {
fmt.Println("Task 4: Query data")
return nil
})
if err := workflow.Run(); err != nil {
fmt.Printf("Error running workflow: %v\n", err)
} else {
fmt.Println("Workflow completed successfully")
}
}
首先,创建一个 docker-compose.yml
文件,定义数据库服务和应用程序服务:
version: '3'
services:
db:
image: "postgres:latest"
environment:
POSTGRES_USER: "user"
POSTGRES_PASSWORD: "password"
POSTGRES_DB: "mydb"
volumes:
- "./data:/var/lib/postgresql/data"
ports:
- "5432:5432"
app:
build: .
depends_on:
- db
environment:
DATABASE_URL: "postgres://user:password@db:5432/mydb?sslmode=disable"
ports:
- "8080:8080"
package main
import (
"database/sql"
"fmt"
"log"
"os"
_ "github.com/lib/pq"
)
func main() {
// 获取数据库连接字符串
databaseURL := os.Getenv("DATABASE_URL")
if databaseURL == "" {
log.Fatal("DATABASE_URL is not set")
}
// 连接到数据库
db, err := sql.Open("postgres", databaseURL)
if err != nil {
log.Fatalf("Error connecting to database: %v", err)
}
defer db.Close()
// 创建表
_, err = db.Exec(`CREATE TABLE IF NOT EXISTS users (id SERIAL PRIMARY KEY, name TEXT)`)
if err != nil {
log.Fatalf("Error creating table: %v", err)
}
// 插入数据
_, err = db.Exec(`INSERT INTO users (name) VALUES ('John Doe')`)
if err != nil {
log.Fatalf("Error inserting data: %v", err)
}
// 查询数据
rows, err := db.Query(`SELECT id, name FROM users`)
if err != nil {
log.Fatalf("Error querying data: %v", err)
}
defer rows.Close()
for rows.Next() {
var id int
var name string
err = rows.Scan(&id, &name)
if err != nil {
log.Fatalf("Error scanning row: %v", err)
}
fmt.Printf("User: %d, %s\n", id, name)
}
if err = rows.Err(); err != nil {
log.Fatalf("Error iterating through rows: %v", err)
}
}
在项目根目录下运行以下命令:
docker-compose up --build
这将启动数据库容器和应用程序容器,并在应用程序容器中运行工作流。应用程序将连接到数据库,创建表、插入数据并查询数据。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。