搜索
首页后端开发Golang使用 Go 构建基于 OTP 的身份验证服务器:部分文件上传和正常关闭

Build an OTP-Based Authentication Server with Go: Part  File Uploads and Graceful Shutdown

本期通过添加文件上传功能、使用 Makefile 简化开发以及实现优雅的服务器关闭来完善我们的 Go 身份验证服务器。 这可以防止突然终止并确保所有正在进行的任务在服务器停止之前完成。

正常关闭实施

新的cmd/api/server.go 文件集中了服务器管理。 Goroutine 监视终止信号(SIGINT、SIGTERM)。收到信号后,它会正常关闭服务器。 评论阐明了每个步骤。

package main

import (
    "context"
    "errors"
    "fmt"
    "net/http"
    "os"
    "os/signal"
    "syscall"
    "time"
)

// ... (Existing application code) ...

func (app *application) serve(router http.Handler) error {
    // Server initialization with timeouts for idle, read, and write operations.
    srv := &http.Server{
        Addr:         fmt.Sprintf(":%d", app.config.port),
        Handler:      app.recoverPanic(app.authenticate(router)),
        IdleTimeout:  time.Minute,
        ReadTimeout:  10 * time.Second,
        WriteTimeout: 30 * time.Second,
    }

    // Channel to manage errors during shutdown.
    shutdownError := make(chan error)

    // Goroutine to listen for termination signals and initiate graceful shutdown.
    go func() {
        quit := make(chan os.Signal, 1)
        signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
        s := <-quit // Wait for signal
        fmt.Println("Shutting down server...")

        // Context with timeout for graceful shutdown.
        ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
        defer cancel()

        // Attempt graceful shutdown.
        shutdownError <- srv.Shutdown(ctx)
    }()

    // Start the server and report any errors.
    fmt.Printf("Starting server on port %d\n", app.config.port)
    err := srv.ListenAndServe()
    if !errors.Is(err, http.ErrServerClosed) {
        return fmt.Errorf("server error: %w", err)
    }
    return <-shutdownError
}

// ... (Rest of application code) ...

main.go 中,将 srv.ListenAndServe() 块替换为 err = app.serve(router); if err != nil { logger.Fatal(err, nil) }。 测试涉及使用重试机制(删除连续重试的凭据)并使用 Ctrl C 中断服务器;它应该等待重试完成后再关闭。

使用 Makefile 自动化任务

A Makefile 自动执行重复命令。 将以下内容添加到项目的 Makefile 中:

# Include variables from the .envrc file
include .envrc

## help: print this help message
.PHONY: help
help:
    @echo 'Usage:'
    @sed -n 's/^##//p' ${MAKEFILE_LIST} | column -t -s ':' | sed -e 's/^/ /'

.PHONY: confirm
confirm:
    @echo -n 'Are you sure? [y/N] ' && read ans && [ $${ans:-N} = y ]

## run/api: run the cmd/api application
.PHONY: run/api
run/api:
    go run ./cmd/api

## db/psql: connect to the database using psql
.PHONY: db/psql
db/psql:
    psql ${GREENLIGHT_DB_DSN}

## db/migrations/new name=: create a new database migration
.PHONY: db/migrations/new
db/migrations/new:
    @echo "Migrating ${name}"
    migrate create -seq -ext=.sql -dir=./migrations ${name}

## db/migrations/up: apply all up database migrations
.PHONY: db/migrations/up
db/migrations/up: confirm
    @echo "Running migrations"
    migrate -path=./migrations -database=${GREENLIGHT_DB_DSN} up

## audit: tidy and vendor dependencies and format, vet and test all code
.PHONY: audit
audit: vendor
    @echo 'Formatting code...'
    go fmt ./...
    @echo 'Vetting code...'
    go vet ./...
    staticcheck ./...
    @echo 'Running tests...'
    go test -race -vet=off ./...

## vendor: tidy and vendor dependencies
.PHONY: vendor
vendor:
    @echo 'Tidying and verifying module dependencies...'
    go mod tidy
    go mod verify
    @echo 'Vendoring dependencies...'
    go mod vendor

## build/api: build the cmd/api application
.PHONY: build/api
build/api:
    @echo 'Building cmd/api...'
    go build -o=./bin/api ./cmd/api
    GOOS=linux GOARCH=amd64 go build -o=./bin/linux_amd64/api ./cmd/api

运行 make helpmake run/apimake db/migrations/new name=my_migrationmake db/migrations/upmake auditmake build/api 等命令。 可以按照此结构添加其他命令。

文件上传和跟踪

新的数据库表跟踪上传的文件:

创建迁移make db/migrations/new name=create-creatives.

000003_create-creatives.up.sql:

CREATE TABLE IF NOT EXISTS creatives (
    id bigserial PRIMARY KEY,
    user_id bigint NOT NULL REFERENCES users ON DELETE CASCADE,
    creative_url text NOT NULL,
    scheduled_at DATE NOT NULL,
    created_at timestamp(0) with time zone NOT NULL DEFAULT NOW()
);

000003_create-creatives.down.sql:

DROP TABLE IF EXISTS creatives;

internal/data/creatives.go:

package data

import (
    "context"
    "database/sql"
    "time"

    "github.com/lib/pq"
)

// ... (Creative struct and CreativeModel struct) ...

func (c *CreativeModel) Insert(creative *Creative) error {
    query := `INSERT INTO creatives (user_id, creative_url, scheduled_at)
            VALUES (, , )
            RETURNING id, created_at`

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()

    args := []interface{}{creative.UserID, creative.CreativeURL, creative.ScheduledAt}
    return c.DB.QueryRowContext(ctx, query, args...).Scan(&creative.ID, &creative.CreatedAt)
}

func (c *CreativeModel) GetScheduledCreatives() (map[string][]Creative, error) {
    query := `
        SELECT id, user_id, creative_url, scheduled_at, created_at 
        FROM creatives 
        WHERE scheduled_at = ANY()
    `

    dates := []time.Time{
        time.Now().Truncate(24 * time.Hour),
        time.Now().AddDate(0, 0, 1).Truncate(24 * time.Hour),
    }

    ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
    defer cancel()

    rows, err := c.DB.QueryContext(ctx, query, pq.Array(dates))
    if err != nil {
        return nil, err
    }
    defer rows.Close()

    creatives := map[string][]Creative{
        "today":    {},
        "tomorrow": {},
    }

    for rows.Next() {
        var creative Creative
        err := rows.Scan(&creative.ID, &creative.UserID, &creative.CreativeURL, &creative.ScheduledAt, &creative.CreatedAt)
        if err != nil {
            return nil, err
        }
        if creative.ScheduledAt.Equal(dates[0]) {
            creatives["today"] = append(creatives["today"], creative)
        } else if creative.ScheduledAt.Equal(dates[1]) {
            creatives["tomorrow"] = append(creatives["tomorrow"], creative)
        }
    }

    return creatives, rows.Err()
}

cmd/api/creatives.go:(处理文件上传和预定广告素材的检索)

package main

import (
    "fmt"
    "io"
    "net/http"
    "os"
    "path"
    "strings"
    "time"

    "github.com/google/uuid"
    "github.com/vishaaxl/cheershare/internal/data"
)

const MaxFileSize = 10 << 20 // 10MB

// ... (Existing code) ...

func (app *application) uploadCreativeHandler(w http.ResponseWriter, r *http.Request) {
    // ... (File upload handling logic) ...
}

func (app *application) getScheduledCreativesHandler(w http.ResponseWriter, r *http.Request) {
    // ... (Retrieve scheduled creatives logic) ...
}

将以下内容添加到您的 main.go 或服务器初始化中以创建上传目录(如果不存在):

uploadDir := "./uploads"
if _, err := os.Stat(uploadDir); os.IsNotExist(err) {
    err := os.MkdirAll(uploadDir, os.ModePerm)
    if err != nil {
        fmt.Println("Unable to create uploads directory:", err)
    }
}

router.HandlerFunc(http.MethodPost, "/upload-creative", app.requireAuthenticatedUser(app.uploadCreativeHandler))
router.HandlerFunc(http.MethodGet, "/scheduled", app.requireAuthenticatedUser(app.getScheduledCreativesHandler))

请记住将占位符注释替换为处理程序中文件处理和错误管理的实际实现细节。 这完成了核心功能,不包括支付处理(将在未来的更新中涵盖)。 所提供的第 3 部分链接将被保留。

以上是使用 Go 构建基于 OTP 的身份验证服务器:部分文件上传和正常关闭的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Go语言包导入:带下划线和不带下划线的区别是什么?Go语言包导入:带下划线和不带下划线的区别是什么?Mar 03, 2025 pm 05:17 PM

本文解释了GO的软件包导入机制:命名imports(例如导入“ fmt”)和空白导入(例如导入_ fmt; fmt;)。 命名导入使包装内容可访问,而空白导入仅执行t

Beego框架中NewFlash()函数如何实现页面间短暂信息传递?Beego框架中NewFlash()函数如何实现页面间短暂信息传递?Mar 03, 2025 pm 05:22 PM

本文解释了Beego的NewFlash()函数,用于Web应用程序中的页间数据传输。 它专注于使用newflash()在控制器之间显示临时消息(成功,错误,警告),并利用会话机制。 Lima

Go语言中如何将MySQL查询结果List转换为自定义结构体切片?Go语言中如何将MySQL查询结果List转换为自定义结构体切片?Mar 03, 2025 pm 05:18 PM

本文详细介绍了MySQL查询结果的有效转换为GO结构切片。 它强调使用数据库/SQL的扫描方法来最佳性能,避免手动解析。 使用DB标签和Robus的结构现场映射的最佳实践

如何编写模拟对象和存根以进行测试?如何编写模拟对象和存根以进行测试?Mar 10, 2025 pm 05:38 PM

本文演示了创建模拟和存根进行单元测试。 它强调使用接口,提供模拟实现的示例,并讨论最佳实践,例如保持模拟集中并使用断言库。 文章

如何定义GO中仿制药的自定义类型约束?如何定义GO中仿制药的自定义类型约束?Mar 10, 2025 pm 03:20 PM

本文探讨了GO的仿制药自定义类型约束。 它详细介绍了界面如何定义通用功能的最低类型要求,从而改善了类型的安全性和代码可重复使用性。 本文还讨论了局限性和最佳实践

Go语言如何便捷地写入文件?Go语言如何便捷地写入文件?Mar 03, 2025 pm 05:15 PM

本文详细介绍了在GO中详细介绍有效的文件,将OS.WriteFile(适用于小文件)与OS.openfile和缓冲写入(最佳大型文件)进行比较。 它强调了使用延迟并检查特定错误的可靠错误处理。

您如何在GO中编写单元测试?您如何在GO中编写单元测试?Mar 21, 2025 pm 06:34 PM

本文讨论了GO中的编写单元测试,涵盖了最佳实践,模拟技术和有效测试管理的工具。

如何使用跟踪工具了解GO应用程序的执行流?如何使用跟踪工具了解GO应用程序的执行流?Mar 10, 2025 pm 05:36 PM

本文使用跟踪工具探讨了GO应用程序执行流。 它讨论了手册和自动仪器技术,比较诸如Jaeger,Zipkin和Opentelemetry之类的工具,并突出显示有效的数据可视化

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
1 个月前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

EditPlus 中文破解版

EditPlus 中文破解版

体积小,语法高亮,不支持代码提示功能

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

VSCode Windows 64位 下载

VSCode Windows 64位 下载

微软推出的免费、功能强大的一款IDE编辑器