GolangNote

Golang笔记

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

Permalink

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

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
}

Related articles

Golang telegram 机器人小试

telegram 的机器人接口很开放,使用简单,100%开放无限制,相对微信服务号、公众号好很多。用来做一些小应用也很方便。下面是使用golang sdk 开发telegram 机器人的经验。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.16.5 Processed in 1ms