Golang笔记

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

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

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 (转载注明出处)
关于GolangNote:记录在工作中使用golang 遇到、面临的相关问题及解决方法。如果你在这里获得一些知识或信息,解决你的编程问题,请考虑捐赠给不幸的人或者你喜欢的慈善机构,除捐赠外,种植树木、志愿服务或减少排碳的行为也很有益处。如果你有任何问题可以在下面 留言
Be the first to comment!
Captcha image
Relative Articles