您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。