Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get rid of global state for config #48

Merged
merged 2 commits into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 18 additions & 6 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,16 @@ import (
"github.com/labstack/echo/v4/middleware"
)

func Run() {
type Params struct {
Host string
Port int
Password string
UseSecureCookie bool
TLSCert string
TLSKey string
}

func Run(params Params) {
r := echo.New()
apiLogger := logx.Logger.With("module", "api")

Expand Down Expand Up @@ -61,7 +70,7 @@ func Run() {
r.Use(middleware.TimeoutWithConfig(middleware.TimeoutConfig{
Timeout: 30 * time.Second,
}))
r.Use(session.Middleware(sessions.NewCookieStore([]byte(conf.Conf.Password))))
r.Use(session.Middleware(sessions.NewCookieStore([]byte(params.Password))))
r.Pre(middleware.RemoveTrailingSlash())
r.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
Expand All @@ -78,7 +87,10 @@ func Run() {
Browse: false,
}))

loginAPI := Session{}
loginAPI := Session{
Password: params.Password,
UseSecureCookie: params.UseSecureCookie,
}
r.POST("/api/sessions", loginAPI.Create)

authed := r.Group("/api", func(next echo.HandlerFunc) echo.HandlerFunc {
Expand Down Expand Up @@ -118,9 +130,9 @@ func Run() {
items.DELETE("/:id", itemAPIHandler.Delete)

var err error
addr := fmt.Sprintf("%s:%d", conf.Conf.Host, conf.Conf.Port)
if conf.Conf.TLSCert != "" {
err = r.StartTLS(addr, conf.Conf.TLSCert, conf.Conf.TLSKey)
addr := fmt.Sprintf("%s:%d", params.Host, params.Port)
if params.TLSCert != "" {
err = r.StartTLS(addr, params.TLSCert, params.TLSKey)
} else {
err = r.Start(addr)
}
Expand Down
11 changes: 6 additions & 5 deletions api/session.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ package api
import (
"net/http"

"github.com/0x2e/fusion/conf"

"github.com/labstack/echo-contrib/session"
"github.com/labstack/echo/v4"
)

type Session struct{}
type Session struct {
Password string
UseSecureCookie bool
}

// sessionKeyName is the name of the key in the session store, and it's also the
// client-visible name of the HTTP cookie for the session.
Expand All @@ -24,7 +25,7 @@ func (s Session) Create(c echo.Context) error {
return err
}

if req.Password != conf.Conf.Password {
if req.Password != s.Password {
return echo.NewHTTPError(http.StatusUnauthorized, "Wrong password")
}

Expand All @@ -33,7 +34,7 @@ func (s Session) Create(c echo.Context) error {
return err
}

if !conf.Conf.SecureCookie {
if !s.UseSecureCookie {
sess.Options.Secure = false
sess.Options.SameSite = http.SameSiteDefaultMode
}
Expand Down
17 changes: 14 additions & 3 deletions cmd/server/server.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"log"
"net/http"
_ "net/http/pprof"

Expand All @@ -20,10 +21,20 @@ func main() {
}()
}

conf.Load()
repo.Init()
config, err := conf.Load()
if err != nil {
log.Fatalf("failed to load configuration: %v", err)
}
repo.Init(config.DB)

go pull.NewPuller(repo.NewFeed(repo.DB), repo.NewItem(repo.DB)).Run()

api.Run()
api.Run(api.Params{
Host: config.Host,
Port: config.Port,
Password: config.Password,
UseSecureCookie: config.SecureCookie,
TLSCert: config.TLSCert,
TLSKey: config.TLSKey,
})
}
39 changes: 17 additions & 22 deletions conf/conf.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,48 +16,43 @@ const (
dotEnvFilename = ".env"
)

var Conf struct {
Host string `env:"HOST" envDefault:"0.0.0.0"`
Port int `env:"PORT" envDefault:"8080"`
Password string `env:"PASSWORD"`
DB string `env:"DB" envDefault:"fusion.db"`

type Conf struct {
Host string `env:"HOST" envDefault:"0.0.0.0"`
Port int `env:"PORT" envDefault:"8080"`
Password string `env:"PASSWORD"`
DB string `env:"DB" envDefault:"fusion.db"`
SecureCookie bool `env:"SECURE_COOKIE" envDefault:"false"`
TLSCert string `env:"TLS_CERT"`
TLSKey string `env:"TLS_KEY"`
}

func Load() {
func Load() (Conf, error) {
if err := godotenv.Load(dotEnvFilename); err != nil {
if !os.IsNotExist(err) {
panic(err)
return Conf{}, err
}
log.Printf("no configuration file found at %s", dotEnvFilename)
} else {
log.Printf("read configuration from %s", dotEnvFilename)
}
if err := env.Parse(&Conf); err != nil {
panic(err)
}
if err := validate(); err != nil {
var conf Conf
if err := env.Parse(&conf); err != nil {
panic(err)
}
if Debug {
fmt.Println(Conf)
fmt.Println(conf)
}
}

func validate() error {
if Conf.Password == "" {
return errors.New("password is required")
if conf.Password == "" {
return Conf{}, errors.New("password is required")
}

if (Conf.TLSCert == "") != (Conf.TLSKey == "") {
return errors.New("missing TLS cert or key file")
if (conf.TLSCert == "") != (conf.TLSKey == "") {
return Conf{}, errors.New("missing TLS cert or key file")
}
if Conf.TLSCert != "" {
Conf.SecureCookie = true
if conf.TLSCert != "" {
conf.SecureCookie = true
}

return nil
return conf, nil
}
5 changes: 2 additions & 3 deletions repo/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"errors"
"log"

"github.com/0x2e/fusion/conf"
"github.com/0x2e/fusion/model"

"github.com/glebarez/sqlite"
Expand All @@ -13,9 +12,9 @@ import (

var DB *gorm.DB

func Init() {
func Init(dbPath string) {
conn, err := gorm.Open(
sqlite.Open(conf.Conf.DB),
sqlite.Open(dbPath),
&gorm.Config{TranslateError: true},
)
if err != nil {
Expand Down
Loading