Skip to content

Commit

Permalink
wip: remove global
Browse files Browse the repository at this point in the history
  • Loading branch information
dhcmrlchtdj committed May 5, 2024
1 parent a2f3acf commit e61c083
Show file tree
Hide file tree
Showing 23 changed files with 289 additions and 95 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ GOFLAGS := -buildvcs=false -buildmode=pie -mod=readonly -trimpath
.PHONY: dev build fmt lint test clean outdated upgrade

build:
cd frontend && make build
# cd frontend && make build
CGO_ENABLED=0 go build $(GOFLAGS) -o _build/ ./cmd/...

dev:
Expand Down
24 changes: 13 additions & 11 deletions cmd/feedbox/init_env.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (

"github.com/dhcmrlchtdj/feedbox/internal/database"
"github.com/dhcmrlchtdj/feedbox/internal/email"
"github.com/dhcmrlchtdj/feedbox/internal/global"
"github.com/dhcmrlchtdj/feedbox/internal/sign"
"github.com/dhcmrlchtdj/feedbox/internal/telegram"
"github.com/dhcmrlchtdj/feedbox/internal/util"
Expand All @@ -37,39 +36,42 @@ func initDatabase(ctx context.Context) {
if err != nil {
panic(err)
}
global.Database = db
database.SetDefault(db)
}

func initEmail() {
global.Email = email.NewDryRun()
if os.Getenv("ENV") == "prod" {
if util.CheckEnvsExist("MAILCHANNELS_URL", "MAILCHANNELS_USERNAME", "MAILCHANNELS_PASSWORD") {
global.Email = email.NewMailChannels(
email.SetDefault(email.NewMailChannels(
os.Getenv("MAILCHANNELS_URL"),
os.Getenv("MAILCHANNELS_USERNAME"),
os.Getenv("MAILCHANNELS_PASSWORD"),
)
))
return
} else if util.CheckEnvsExist("MAILGUN_DOMAIN", "MAILGUN_API_KEY", "MAILGUN_FROM") {
global.Email = email.NewMailgun(
email.SetDefault(email.NewMailgun(
os.Getenv("MAILGUN_DOMAIN"),
os.Getenv("MAILGUN_API_KEY"),
os.Getenv("MAILGUN_FROM"),
)
))
return
}
}
email.SetDefault(email.NewDryRun())
}

func initTelegram() {
global.Telegram = telegram.NewDryRun()
if os.Getenv("ENV") == "prod" {
util.CheckEnvs("SERVER")
if util.CheckEnvsExist("TELEGRAM_BOT_NAME", "TELEGRAM_BOT_TOKEN") {
global.Telegram = telegram.NewHTTPClient(
telegram.SetDefault(telegram.NewHTTPClient(
os.Getenv("TELEGRAM_BOT_NAME"),
os.Getenv("TELEGRAM_BOT_TOKEN"),
)
))
return
}
}
telegram.SetDefault(telegram.NewDryRun())
}

func initSign() {
Expand All @@ -78,7 +80,7 @@ func initSign() {
if err != nil {
panic(err)
}
global.Sign = s
sign.SetDefault(s)
}

///
Expand Down
16 changes: 13 additions & 3 deletions cmd/feedbox/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,16 @@ import (
"context"
"flag"
"fmt"
"log/slog"
"net"
"os"
"sync"
"time"

"github.com/phuslu/log"
"github.com/rs/zerolog"

"github.com/dhcmrlchtdj/feedbox/internal/global"
"github.com/dhcmrlchtdj/feedbox/internal/database"
"github.com/dhcmrlchtdj/feedbox/internal/util"
"github.com/dhcmrlchtdj/feedbox/server"
"github.com/dhcmrlchtdj/feedbox/worker"
Expand Down Expand Up @@ -40,10 +42,18 @@ func startServerAndWorker() {
ctx, cancel := context.WithCancel(context.Background())
ctx = logger.WithContext(ctx)

plog := log.Logger{
Level: log.InfoLevel,
TimeField: "date",
TimeFormat: "2006-01-02",
Caller: 1,
}
slog.SetDefault(plog.Slog())

initEnv()
initLogger()
initDatabase(ctx)
defer global.Database.Close()
defer database.Close()
initEmail()
initTelegram()
initSign()
Expand Down Expand Up @@ -76,7 +86,7 @@ func startServer() {
initEnv()
initLogger()
initDatabase(ctx)
defer global.Database.Close()
defer database.Close()
initEmail()
initTelegram()
initSign()
Expand Down
1 change: 1 addition & 0 deletions dotenv.example
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
DATABASE_URL="sqlite://:memory:"
DATABASE_URL="sqlite:///path/to/feedbox.db"
HOST="0.0.0.0"
PORT=8000
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/ncruces/go-strftime v0.1.9 // indirect
github.com/phuslu/log v1.0.95 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
github.com/rivo/uniseg v0.4.7 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
github.com/phuslu/log v1.0.95 h1:EysMtO1b2EePFuToRLs959OCoYGMIpskv9Zc5GEYuUM=
github.com/phuslu/log v1.0.95/go.mod h1:F8osGJADo5qLK/0F88djWwdyoZZ9xDJQL1HYRHFEkS0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
Expand Down
88 changes: 88 additions & 0 deletions internal/database/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package database
import (
"context"
"strings"
"sync/atomic"
"time"

"github.com/dhcmrlchtdj/feedbox/internal/database/common"
Expand Down Expand Up @@ -31,6 +32,93 @@ type Database interface {

///

var defaultImpl atomic.Pointer[Database]

func init() {
var dryrun Database
dryrun, err := New(context.Background(), "sqlite://:memory:")
if err != nil {
panic(err)
}
defaultImpl.Store(&dryrun)
}

func Default() Database {
return *defaultImpl.Load()
}

func SetDefault(c Database) {
defaultImpl.Store(&c)
}

///

func Close() {
Default().Close()
}

func GetUserByID(ctx context.Context, id int64) (*User, error) {
return Default().GetUserByID(ctx, id)
}

func GetOrCreateUserByGithub(ctx context.Context, githubID string, email string) (*User, error) {
return Default().GetOrCreateUserByGithub(ctx, githubID, email)
}

func GetOrCreateUserByTelegram(ctx context.Context, chatID string) (*User, error) {
return GetOrCreateUserByTelegram(ctx, chatID)
}

func GetFeedIDByURL(ctx context.Context, url string) (int64, error) {
return Default().GetFeedIDByURL(ctx, url)
}

func GetFeedByUser(ctx context.Context, userID int64, orderBy string) ([]Feed, error) {
return Default().GetFeedByUser(ctx, userID, orderBy)
}

func GetActiveFeeds(ctx context.Context) ([]Feed, error) {
return Default().GetActiveFeeds(ctx)
}

func AddFeedLinks(ctx context.Context, id int64, links []string, updated *time.Time, etag string) error {
return Default().AddFeedLinks(ctx, id, links, updated, etag)
}

func SetFeedUpdated(ctx context.Context, id int64, updated *time.Time, etag string) error {
return Default().SetFeedUpdated(ctx, id, updated, etag)
}

func GetLinks(ctx context.Context, feedID int64) ([]string, error) {
return Default().GetLinks(ctx, feedID)
}

func GetSubscribers(ctx context.Context, feedID int64) ([]User, error) {
return Default().GetSubscribers(ctx, feedID)
}

func Subscribe(ctx context.Context, userID int64, feedID int64) error {
return Default().Subscribe(ctx, userID, feedID)
}

func Unsubscribe(ctx context.Context, userID int64, feedID int64) error {
return Default().Unsubscribe(ctx, userID, feedID)
}

func UnsubscribeAll(ctx context.Context, userID int64) error {
return Default().UnsubscribeAll(ctx, userID)
}

func SubscribeURL(ctx context.Context, userID int64, url string) error {
return Default().SubscribeURL(ctx, userID, url)
}

func SubscribeURLs(ctx context.Context, userID int64, urls []string) error {
return Default().SubscribeURLs(ctx, userID, urls)
}

///

type (
User = common.User
Feed = common.Feed
Expand Down
28 changes: 27 additions & 1 deletion internal/email/export.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,33 @@
package email

import "context"
import (
"context"
"sync/atomic"
)

type Client interface {
Send(ctx context.Context, addr string, subject string, text string) error
}

///

var defaultImpl atomic.Pointer[Client]

func init() {
var dryrun Client = NewDryRun()
defaultImpl.Store(&dryrun)
}

func Default() Client {
return *defaultImpl.Load()
}

func SetDefault(c Client) {
defaultImpl.Store(&c)
}

///

func Send(ctx context.Context, addr string, subject string, text string) error {
return Default().Send(ctx, addr, subject, text)
}
15 changes: 0 additions & 15 deletions internal/global/global.go

This file was deleted.

41 changes: 41 additions & 0 deletions internal/sign/export.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,49 @@
package sign

import "sync/atomic"

type Client interface {
Encode(plaintext []byte) ([]byte, error)
Decode(data []byte) ([]byte, error)
DecodeFromHex(hexData string) ([]byte, error)
EncodeToHex(plaintext []byte) (string, error)
}

///

var defaultImpl atomic.Pointer[Client]

func init() {
var dryrun Client
dryrun, err := NewWithPassword("dryrun")
if err != nil {
panic(err)
}
defaultImpl.Store(&dryrun)
}

func Default() Client {
return *defaultImpl.Load()
}

func SetDefault(c Client) {
defaultImpl.Store(&c)
}

///

func Encode(plaintext []byte) ([]byte, error) {
return Default().Encode(plaintext)
}

func Decode(data []byte) ([]byte, error) {
return Default().Decode(data)
}

func DecodeFromHex(hexData string) ([]byte, error) {
return Default().DecodeFromHex(hexData)
}

func EncodeToHex(plaintext []byte) (string, error) {
return Default().EncodeToHex(plaintext)
}
Loading

0 comments on commit e61c083

Please sign in to comment.