GolangNote

Golang笔记

golang webserver 引入数据库连接的较好方式

Permalink

这是个人认为golang webserver 引入数据库连接的较好方式,代码也比较优美

Go: 引入数据库连接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main

import (
	"database/sql"
	"net/http"
	"strconv"

	_ "github.com/go-sql-driver/mysql"
)

type Dependencies struct {
	Database *sql.DB
	// also logging
	// and metrics
	// and service consumers
	// whatever
}

func (d Dependencies) GetDatabase() *sql.DB {
	return d.Database
}

type APIv1 struct {
	Dependencies
	// any APIv1-specific dependencies
}

type Databaser interface {
	GetDatabase() *sql.DB
}

func main() {
	myDB, err := sql.Open("mysql", "mysql-dsn-goes-here")
	if err != nil {
		panic(err)
	}
	coreDeps := Dependencies{Database: myDB}
	apiv1 := APIv1{Dependencies: coreDeps}
	http.Handle("/v1", apiv1)
	// ListenAndServe, you know the rest
}

func minGophersMiddleware(d Databaser, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// call our handler only if there are more than 5 gophers
		db := d.GetDatabase()
		count, err := getCount(db)
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		if count < 5 {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte("Error: not enough gophers"))
			return
		}
		next.ServeHTTP(w, r)
	})
}

func (a APIv1) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	// use a router package here
	// in this example we’re just gonna respond with the same
	// handler to every request
	minGophersMiddleware(a.Dependencies, http.HandlerFunc(a.handler)).ServeHTTP(w, r)
}

func (a APIv1) handler(w http.ResponseWriter, r *http.Request) {
	count, err := getCount(a.Database)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}
	w.Write([]byte(strconv.Itoa(count) + " gophers"))
}

func getCount(db *sql.DB) (int, error) {
	var count int
	err := db.QueryRow("SELECT COUNT(*) FROM animals WHERE name=?", "gopher").Scan(&count)
	return count, err
}

本文网址: https://golangnote.com/topic/176.html 转摘请注明来源

Related articles

Golang 数据库 Bolt 碎片整理

Bolt 是一个优秀、纯 Go 实现、支持 ACID 事务的嵌入式 Key/Value 数据库。但在使用过程中会有很多空间碎片。一般数据库占用的空间是元数据空间的 1.5~4 倍。Bolt 没有内置的压缩功能,需要手动压缩。...

Write a Comment to "golang webserver 引入数据库连接的较好方式"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 0ms