mirror of
https://github.com/gogs/gogs.git
synced 2025-12-24 01:00:00 +01:00
conf: overhaul server settings (#5928)
* conf: rename package * Requires Go 1.12 * Fix lint * Fix lint * Overhaul * db: fix tests * Save my work * Fix tests * Server.UnixSocketPermission * Server.LocalRootURL * SSH settings * Server.OfflineMode * Save my work * App.Version * Remove [server] STATIC_ROOT_PATH * Server.LandingURL
This commit is contained in:
@@ -9,10 +9,11 @@ import (
|
||||
"reflect"
|
||||
"runtime"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/urfave/cli"
|
||||
|
||||
"gogs.io/gogs/internal/conf"
|
||||
"gogs.io/gogs/internal/db"
|
||||
"gogs.io/gogs/internal/setting"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -133,18 +134,18 @@ to make automatic initialization process more smoothly`,
|
||||
|
||||
func runCreateUser(c *cli.Context) error {
|
||||
if !c.IsSet("name") {
|
||||
return fmt.Errorf("Username is not specified")
|
||||
return errors.New("Username is not specified")
|
||||
} else if !c.IsSet("password") {
|
||||
return fmt.Errorf("Password is not specified")
|
||||
return errors.New("Password is not specified")
|
||||
} else if !c.IsSet("email") {
|
||||
return fmt.Errorf("Email is not specified")
|
||||
return errors.New("Email is not specified")
|
||||
}
|
||||
|
||||
if c.IsSet("config") {
|
||||
setting.CustomConf = c.String("config")
|
||||
err := conf.Init(c.String("config"))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "init configuration")
|
||||
}
|
||||
|
||||
setting.Init()
|
||||
db.LoadConfigs()
|
||||
db.SetEngine()
|
||||
|
||||
@@ -164,11 +165,11 @@ func runCreateUser(c *cli.Context) error {
|
||||
|
||||
func adminDashboardOperation(operation func() error, successMessage string) func(*cli.Context) error {
|
||||
return func(c *cli.Context) error {
|
||||
if c.IsSet("config") {
|
||||
setting.CustomConf = c.String("config")
|
||||
err := conf.Init(c.String("config"))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "init configuration")
|
||||
}
|
||||
|
||||
setting.Init()
|
||||
db.LoadConfigs()
|
||||
db.SetEngine()
|
||||
|
||||
|
||||
@@ -9,16 +9,18 @@ import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/unknwon/cae/zip"
|
||||
"github.com/unknwon/com"
|
||||
"github.com/urfave/cli"
|
||||
"gopkg.in/ini.v1"
|
||||
log "unknwon.dev/clog/v2"
|
||||
|
||||
"gogs.io/gogs/internal/conf"
|
||||
"gogs.io/gogs/internal/db"
|
||||
"gogs.io/gogs/internal/setting"
|
||||
)
|
||||
|
||||
var Backup = cli.Command{
|
||||
@@ -44,10 +46,12 @@ const _ARCHIVE_ROOT_DIR = "gogs-backup"
|
||||
|
||||
func runBackup(c *cli.Context) error {
|
||||
zip.Verbose = c.Bool("verbose")
|
||||
if c.IsSet("config") {
|
||||
setting.CustomConf = c.String("config")
|
||||
|
||||
err := conf.Init(c.String("config"))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "init configuration")
|
||||
}
|
||||
setting.Init()
|
||||
|
||||
db.LoadConfigs()
|
||||
db.SetEngine()
|
||||
|
||||
@@ -66,12 +70,12 @@ func runBackup(c *cli.Context) error {
|
||||
metadata := ini.Empty()
|
||||
metadata.Section("").Key("VERSION").SetValue(com.ToStr(_CURRENT_BACKUP_FORMAT_VERSION))
|
||||
metadata.Section("").Key("DATE_TIME").SetValue(time.Now().String())
|
||||
metadata.Section("").Key("GOGS_VERSION").SetValue(setting.AppVersion)
|
||||
metadata.Section("").Key("GOGS_VERSION").SetValue(conf.App.Version)
|
||||
if err = metadata.SaveTo(metaFile); err != nil {
|
||||
log.Fatal("Failed to save metadata '%s': %v", metaFile, err)
|
||||
}
|
||||
|
||||
archiveName := path.Join(c.String("target"), c.String("archive-name"))
|
||||
archiveName := filepath.Join(c.String("target"), c.String("archive-name"))
|
||||
log.Info("Packing backup files to: %s", archiveName)
|
||||
|
||||
z, err := zip.Create(archiveName)
|
||||
@@ -83,7 +87,7 @@ func runBackup(c *cli.Context) error {
|
||||
}
|
||||
|
||||
// Database
|
||||
dbDir := path.Join(rootDir, "db")
|
||||
dbDir := filepath.Join(rootDir, "db")
|
||||
if err = db.DumpDatabase(dbDir); err != nil {
|
||||
log.Fatal("Failed to dump database: %v", err)
|
||||
}
|
||||
@@ -93,7 +97,7 @@ func runBackup(c *cli.Context) error {
|
||||
|
||||
// Custom files
|
||||
if !c.Bool("database-only") {
|
||||
if err = z.AddDir(_ARCHIVE_ROOT_DIR+"/custom", setting.CustomPath); err != nil {
|
||||
if err = z.AddDir(_ARCHIVE_ROOT_DIR+"/custom", conf.CustomDir()); err != nil {
|
||||
log.Fatal("Failed to include 'custom': %v", err)
|
||||
}
|
||||
}
|
||||
@@ -101,7 +105,7 @@ func runBackup(c *cli.Context) error {
|
||||
// Data files
|
||||
if !c.Bool("database-only") {
|
||||
for _, dir := range []string{"attachments", "avatars", "repo-avatars"} {
|
||||
dirPath := path.Join(setting.AppDataPath, dir)
|
||||
dirPath := filepath.Join(conf.Server.AppDataPath, dir)
|
||||
if !com.IsDir(dirPath) {
|
||||
continue
|
||||
}
|
||||
@@ -114,9 +118,9 @@ func runBackup(c *cli.Context) error {
|
||||
|
||||
// Repositories
|
||||
if !c.Bool("exclude-repos") && !c.Bool("database-only") {
|
||||
reposDump := path.Join(rootDir, "repositories.zip")
|
||||
log.Info("Dumping repositories in '%s'", setting.RepoRootPath)
|
||||
if err = zip.PackTo(setting.RepoRootPath, reposDump, true); err != nil {
|
||||
reposDump := filepath.Join(rootDir, "repositories.zip")
|
||||
log.Info("Dumping repositories in '%s'", conf.RepoRootPath)
|
||||
if err = zip.PackTo(conf.RepoRootPath, reposDump, true); err != nil {
|
||||
log.Fatal("Failed to dump repositories: %v", err)
|
||||
}
|
||||
log.Info("Repositories dumped to: %s", reposDump)
|
||||
|
||||
@@ -20,11 +20,11 @@ import (
|
||||
|
||||
"github.com/gogs/git-module"
|
||||
|
||||
"gogs.io/gogs/internal/conf"
|
||||
"gogs.io/gogs/internal/db"
|
||||
"gogs.io/gogs/internal/db/errors"
|
||||
"gogs.io/gogs/internal/httplib"
|
||||
"gogs.io/gogs/internal/mailer"
|
||||
"gogs.io/gogs/internal/setting"
|
||||
"gogs.io/gogs/internal/template"
|
||||
)
|
||||
|
||||
@@ -141,7 +141,7 @@ func runHookPreReceive(c *cli.Context) error {
|
||||
}
|
||||
|
||||
var hookCmd *exec.Cmd
|
||||
if setting.IsWindows {
|
||||
if conf.IsWindowsRuntime() {
|
||||
hookCmd = exec.Command("bash.exe", "custom_hooks/pre-receive")
|
||||
} else {
|
||||
hookCmd = exec.Command(customHooksPath)
|
||||
@@ -175,7 +175,7 @@ func runHookUpdate(c *cli.Context) error {
|
||||
}
|
||||
|
||||
var hookCmd *exec.Cmd
|
||||
if setting.IsWindows {
|
||||
if conf.IsWindowsRuntime() {
|
||||
hookCmd = exec.Command("bash.exe", append([]string{"custom_hooks/update"}, args...)...)
|
||||
} else {
|
||||
hookCmd = exec.Command(customHooksPath, args...)
|
||||
@@ -198,7 +198,7 @@ func runHookPostReceive(c *cli.Context) error {
|
||||
|
||||
// Post-receive hook does more than just gather Git information,
|
||||
// so we need to setup additional services for email notifications.
|
||||
setting.NewPostReceiveHookServices()
|
||||
conf.NewPostReceiveHookServices()
|
||||
mailer.NewContext()
|
||||
|
||||
isWiki := strings.Contains(os.Getenv(db.ENV_REPO_CUSTOM_HOOKS_PATH), ".wiki.git/")
|
||||
@@ -233,7 +233,7 @@ func runHookPostReceive(c *cli.Context) error {
|
||||
}
|
||||
|
||||
// Ask for running deliver hook and test pull request tasks
|
||||
reqURL := setting.LocalURL + options.RepoUserName + "/" + options.RepoName + "/tasks/trigger?branch=" +
|
||||
reqURL := conf.Server.LocalRootURL + options.RepoUserName + "/" + options.RepoName + "/tasks/trigger?branch=" +
|
||||
template.EscapePound(strings.TrimPrefix(options.RefFullName, git.BRANCH_PREFIX)) +
|
||||
"&secret=" + os.Getenv(db.ENV_REPO_OWNER_SALT_MD5) +
|
||||
"&pusher=" + os.Getenv(db.ENV_AUTH_USER_ID)
|
||||
@@ -258,7 +258,7 @@ func runHookPostReceive(c *cli.Context) error {
|
||||
}
|
||||
|
||||
var hookCmd *exec.Cmd
|
||||
if setting.IsWindows {
|
||||
if conf.IsWindowsRuntime() {
|
||||
hookCmd = exec.Command("bash.exe", "custom_hooks/post-receive")
|
||||
} else {
|
||||
hookCmd = exec.Command(customHooksPath)
|
||||
|
||||
@@ -7,16 +7,16 @@ package cmd
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"github.com/unknwon/com"
|
||||
"github.com/urfave/cli"
|
||||
|
||||
"gogs.io/gogs/internal/setting"
|
||||
"gogs.io/gogs/internal/conf"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -54,12 +54,11 @@ func runImportLocale(c *cli.Context) error {
|
||||
return fmt.Errorf("target directory %q does not exist or is not a directory", c.String("target"))
|
||||
}
|
||||
|
||||
if c.IsSet("config") {
|
||||
setting.CustomConf = c.String("config")
|
||||
err := conf.Init(c.String("config"))
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "init configuration")
|
||||
}
|
||||
|
||||
setting.Init()
|
||||
|
||||
now := time.Now()
|
||||
|
||||
line := make([]byte, 0, 100)
|
||||
@@ -67,7 +66,7 @@ func runImportLocale(c *cli.Context) error {
|
||||
escapedQuotes := []byte(`\"`)
|
||||
regularQuotes := []byte(`"`)
|
||||
// Cut out en-US.
|
||||
for _, lang := range setting.Langs[1:] {
|
||||
for _, lang := range conf.Langs[1:] {
|
||||
name := fmt.Sprintf("locale_%s.ini", lang)
|
||||
source := filepath.Join(c.String("source"), name)
|
||||
target := filepath.Join(c.String("target"), name)
|
||||
|
||||
@@ -7,16 +7,18 @@ package cmd
|
||||
import (
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/mcuadros/go-version"
|
||||
"github.com/pkg/errors"
|
||||
"github.com/unknwon/cae/zip"
|
||||
"github.com/unknwon/com"
|
||||
"github.com/urfave/cli"
|
||||
"gopkg.in/ini.v1"
|
||||
log "unknwon.dev/clog/v2"
|
||||
|
||||
"gogs.io/gogs/internal/conf"
|
||||
"gogs.io/gogs/internal/db"
|
||||
"gogs.io/gogs/internal/setting"
|
||||
)
|
||||
|
||||
var Restore = cli.Command{
|
||||
@@ -59,7 +61,7 @@ func runRestore(c *cli.Context) error {
|
||||
defer os.RemoveAll(archivePath)
|
||||
|
||||
// Check backup version
|
||||
metaFile := path.Join(archivePath, "metadata.ini")
|
||||
metaFile := filepath.Join(archivePath, "metadata.ini")
|
||||
if !com.IsExist(metaFile) {
|
||||
log.Fatal("File 'metadata.ini' is missing")
|
||||
}
|
||||
@@ -68,8 +70,8 @@ func runRestore(c *cli.Context) error {
|
||||
log.Fatal("Failed to load metadata '%s': %v", metaFile, err)
|
||||
}
|
||||
backupVersion := metadata.Section("").Key("GOGS_VERSION").MustString("999.0")
|
||||
if version.Compare(setting.AppVersion, backupVersion, "<") {
|
||||
log.Fatal("Current Gogs version is lower than backup version: %s < %s", setting.AppVersion, backupVersion)
|
||||
if version.Compare(conf.App.Version, backupVersion, "<") {
|
||||
log.Fatal("Current Gogs version is lower than backup version: %s < %s", conf.App.Version, backupVersion)
|
||||
}
|
||||
formatVersion := metadata.Section("").Key("VERSION").MustInt()
|
||||
if formatVersion == 0 {
|
||||
@@ -82,15 +84,21 @@ func runRestore(c *cli.Context) error {
|
||||
|
||||
// If config file is not present in backup, user must set this file via flag.
|
||||
// Otherwise, it's optional to set config file flag.
|
||||
configFile := path.Join(archivePath, "custom/conf/app.ini")
|
||||
configFile := filepath.Join(archivePath, "custom", "conf", "app.ini")
|
||||
var customConf string
|
||||
if c.IsSet("config") {
|
||||
setting.CustomConf = c.String("config")
|
||||
customConf = c.String("config")
|
||||
} else if !com.IsExist(configFile) {
|
||||
log.Fatal("'--config' is not specified and custom config file is not found in backup")
|
||||
} else {
|
||||
setting.CustomConf = configFile
|
||||
customConf = configFile
|
||||
}
|
||||
setting.Init()
|
||||
|
||||
err = conf.Init(customConf)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "init configuration")
|
||||
}
|
||||
|
||||
db.LoadConfigs()
|
||||
db.SetEngine()
|
||||
|
||||
@@ -102,27 +110,27 @@ func runRestore(c *cli.Context) error {
|
||||
|
||||
// Custom files
|
||||
if !c.Bool("database-only") {
|
||||
if com.IsExist(setting.CustomPath) {
|
||||
if err = os.Rename(setting.CustomPath, setting.CustomPath+".bak"); err != nil {
|
||||
if com.IsExist(conf.CustomDir()) {
|
||||
if err = os.Rename(conf.CustomDir(), conf.CustomDir()+".bak"); err != nil {
|
||||
log.Fatal("Failed to backup current 'custom': %v", err)
|
||||
}
|
||||
}
|
||||
if err = os.Rename(path.Join(archivePath, "custom"), setting.CustomPath); err != nil {
|
||||
if err = os.Rename(filepath.Join(archivePath, "custom"), conf.CustomDir()); err != nil {
|
||||
log.Fatal("Failed to import 'custom': %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Data files
|
||||
if !c.Bool("database-only") {
|
||||
os.MkdirAll(setting.AppDataPath, os.ModePerm)
|
||||
_ = os.MkdirAll(conf.Server.AppDataPath, os.ModePerm)
|
||||
for _, dir := range []string{"attachments", "avatars", "repo-avatars"} {
|
||||
// Skip if backup archive does not have corresponding data
|
||||
srcPath := path.Join(archivePath, "data", dir)
|
||||
srcPath := filepath.Join(archivePath, "data", dir)
|
||||
if !com.IsDir(srcPath) {
|
||||
continue
|
||||
}
|
||||
|
||||
dirPath := path.Join(setting.AppDataPath, dir)
|
||||
dirPath := filepath.Join(conf.Server.AppDataPath, dir)
|
||||
if com.IsExist(dirPath) {
|
||||
if err = os.Rename(dirPath, dirPath+".bak"); err != nil {
|
||||
log.Fatal("Failed to backup current 'data': %v", err)
|
||||
@@ -135,9 +143,9 @@ func runRestore(c *cli.Context) error {
|
||||
}
|
||||
|
||||
// Repositories
|
||||
reposPath := path.Join(archivePath, "repositories.zip")
|
||||
reposPath := filepath.Join(archivePath, "repositories.zip")
|
||||
if !c.Bool("exclude-repos") && !c.Bool("database-only") && com.IsExist(reposPath) {
|
||||
if err := zip.ExtractTo(reposPath, path.Dir(setting.RepoRootPath)); err != nil {
|
||||
if err := zip.ExtractTo(reposPath, filepath.Dir(conf.RepoRootPath)); err != nil {
|
||||
log.Fatal("Failed to extract 'repositories.zip': %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,9 +16,9 @@ import (
|
||||
"github.com/urfave/cli"
|
||||
log "unknwon.dev/clog/v2"
|
||||
|
||||
"gogs.io/gogs/internal/conf"
|
||||
"gogs.io/gogs/internal/db"
|
||||
"gogs.io/gogs/internal/db/errors"
|
||||
"gogs.io/gogs/internal/setting"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -39,7 +39,7 @@ func fail(userMessage, logMessage string, args ...interface{}) {
|
||||
fmt.Fprintln(os.Stderr, "Gogs:", userMessage)
|
||||
|
||||
if len(logMessage) > 0 {
|
||||
if !setting.ProdMode {
|
||||
if !conf.IsProdMode() {
|
||||
fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
|
||||
}
|
||||
log.Fatal(logMessage, args...)
|
||||
@@ -49,22 +49,26 @@ func fail(userMessage, logMessage string, args ...interface{}) {
|
||||
}
|
||||
|
||||
func setup(c *cli.Context, logPath string, connectDB bool) {
|
||||
var customConf string
|
||||
if c.IsSet("config") {
|
||||
setting.CustomConf = c.String("config")
|
||||
customConf = c.String("config")
|
||||
} else if c.GlobalIsSet("config") {
|
||||
setting.CustomConf = c.GlobalString("config")
|
||||
customConf = c.GlobalString("config")
|
||||
}
|
||||
|
||||
setting.Init()
|
||||
err := conf.Init(customConf)
|
||||
if err != nil {
|
||||
fail("Internal error", "Failed to init configuration: %v", err)
|
||||
}
|
||||
|
||||
level := log.LevelTrace
|
||||
if setting.ProdMode {
|
||||
if conf.IsProdMode() {
|
||||
level = log.LevelError
|
||||
}
|
||||
|
||||
err := log.NewFile(log.FileConfig{
|
||||
err = log.NewFile(log.FileConfig{
|
||||
Level: level,
|
||||
Filename: filepath.Join(setting.LogRootPath, logPath),
|
||||
Filename: filepath.Join(conf.LogRootPath, logPath),
|
||||
FileRotationConfig: log.FileRotationConfig{
|
||||
Rotate: true,
|
||||
Daily: true,
|
||||
@@ -72,8 +76,7 @@ func setup(c *cli.Context, logPath string, connectDB bool) {
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
log.Fatal("Failed to init file logger: %v", err)
|
||||
return
|
||||
fail("Internal error", "Failed to init file logger: %v", err)
|
||||
}
|
||||
log.Remove(log.DefaultConsoleName) // Remove the primary logger
|
||||
|
||||
@@ -83,13 +86,12 @@ func setup(c *cli.Context, logPath string, connectDB bool) {
|
||||
|
||||
db.LoadConfigs()
|
||||
|
||||
if setting.UseSQLite3 {
|
||||
workDir, _ := setting.WorkDir()
|
||||
os.Chdir(workDir)
|
||||
if conf.UseSQLite3 {
|
||||
_ = os.Chdir(conf.WorkDir())
|
||||
}
|
||||
|
||||
if err := db.SetEngine(); err != nil {
|
||||
fail("Internal error", "SetEngine: %v", err)
|
||||
fail("Internal error", "Failed to set database engine: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,7 +132,7 @@ var (
|
||||
func runServ(c *cli.Context) error {
|
||||
setup(c, "serv.log", true)
|
||||
|
||||
if setting.SSH.Disabled {
|
||||
if conf.SSH.Disabled {
|
||||
println("Gogs: SSH has been disabled")
|
||||
return nil
|
||||
}
|
||||
@@ -220,12 +222,12 @@ func runServ(c *cli.Context) error {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
setting.NewService()
|
||||
conf.NewService()
|
||||
// Check if the key can access to the repository in case of it is a deploy key (a deploy keys != user key).
|
||||
// A deploy key doesn't represent a signed in user, so in a site with Service.RequireSignInView activated
|
||||
// we should give read access only in repositories where this deploy key is in use. In other case, a server
|
||||
// or system using an active deploy key can get read access to all the repositories in a Gogs service.
|
||||
if key.IsDeployKey() && setting.Service.RequireSignInView {
|
||||
if key.IsDeployKey() && conf.Service.RequireSignInView {
|
||||
checkDeployKey(key, repo)
|
||||
}
|
||||
}
|
||||
@@ -244,7 +246,7 @@ func runServ(c *cli.Context) error {
|
||||
}
|
||||
|
||||
// Special handle for Windows.
|
||||
if setting.IsWindows {
|
||||
if conf.IsWindowsRuntime() {
|
||||
verb = strings.Replace(verb, "-", " ", 1)
|
||||
}
|
||||
|
||||
@@ -265,7 +267,7 @@ func runServ(c *cli.Context) error {
|
||||
RepoPath: repo.RepoPath(),
|
||||
})...)
|
||||
}
|
||||
gitCmd.Dir = setting.RepoRootPath
|
||||
gitCmd.Dir = conf.RepoRootPath
|
||||
gitCmd.Stdout = os.Stdout
|
||||
gitCmd.Stdin = os.Stdin
|
||||
gitCmd.Stderr = os.Stderr
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/fcgi"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/go-macaron/binding"
|
||||
@@ -29,9 +29,9 @@ import (
|
||||
"gopkg.in/macaron.v1"
|
||||
log "unknwon.dev/clog/v2"
|
||||
|
||||
"gogs.io/gogs/internal/assets/conf"
|
||||
"gogs.io/gogs/internal/assets/public"
|
||||
"gogs.io/gogs/internal/assets/templates"
|
||||
"gogs.io/gogs/internal/conf"
|
||||
"gogs.io/gogs/internal/context"
|
||||
"gogs.io/gogs/internal/db"
|
||||
"gogs.io/gogs/internal/form"
|
||||
@@ -42,7 +42,6 @@ import (
|
||||
"gogs.io/gogs/internal/route/org"
|
||||
"gogs.io/gogs/internal/route/repo"
|
||||
"gogs.io/gogs/internal/route/user"
|
||||
"gogs.io/gogs/internal/setting"
|
||||
"gogs.io/gogs/internal/template"
|
||||
)
|
||||
|
||||
@@ -61,58 +60,58 @@ and it takes care of all the other things for you`,
|
||||
// newMacaron initializes Macaron instance.
|
||||
func newMacaron() *macaron.Macaron {
|
||||
m := macaron.New()
|
||||
if !setting.DisableRouterLog {
|
||||
if !conf.Server.DisableRouterLog {
|
||||
m.Use(macaron.Logger())
|
||||
}
|
||||
m.Use(macaron.Recovery())
|
||||
if setting.EnableGzip {
|
||||
if conf.Server.EnableGzip {
|
||||
m.Use(gzip.Gziper())
|
||||
}
|
||||
if setting.Protocol == setting.SCHEME_FCGI {
|
||||
m.SetURLPrefix(setting.AppSubURL)
|
||||
if conf.Server.Protocol == "fcgi" {
|
||||
m.SetURLPrefix(conf.Server.Subpath)
|
||||
}
|
||||
|
||||
// Register custom middleware first to make it possible to override files under "public".
|
||||
m.Use(macaron.Static(
|
||||
path.Join(setting.CustomPath, "public"),
|
||||
filepath.Join(conf.CustomDir(), "public"),
|
||||
macaron.StaticOptions{
|
||||
SkipLogging: setting.DisableRouterLog,
|
||||
SkipLogging: conf.Server.DisableRouterLog,
|
||||
},
|
||||
))
|
||||
var publicFs http.FileSystem
|
||||
if !setting.LoadAssetsFromDisk {
|
||||
if !conf.Server.LoadAssetsFromDisk {
|
||||
publicFs = public.NewFileSystem()
|
||||
}
|
||||
m.Use(macaron.Static(
|
||||
path.Join(setting.StaticRootPath, "public"),
|
||||
filepath.Join(conf.WorkDir(), "public"),
|
||||
macaron.StaticOptions{
|
||||
SkipLogging: setting.DisableRouterLog,
|
||||
SkipLogging: conf.Server.DisableRouterLog,
|
||||
FileSystem: publicFs,
|
||||
},
|
||||
))
|
||||
|
||||
m.Use(macaron.Static(
|
||||
setting.AvatarUploadPath,
|
||||
conf.AvatarUploadPath,
|
||||
macaron.StaticOptions{
|
||||
Prefix: db.USER_AVATAR_URL_PREFIX,
|
||||
SkipLogging: setting.DisableRouterLog,
|
||||
SkipLogging: conf.Server.DisableRouterLog,
|
||||
},
|
||||
))
|
||||
m.Use(macaron.Static(
|
||||
setting.RepositoryAvatarUploadPath,
|
||||
conf.RepositoryAvatarUploadPath,
|
||||
macaron.StaticOptions{
|
||||
Prefix: db.REPO_AVATAR_URL_PREFIX,
|
||||
SkipLogging: setting.DisableRouterLog,
|
||||
SkipLogging: conf.Server.DisableRouterLog,
|
||||
},
|
||||
))
|
||||
|
||||
renderOpt := macaron.RenderOptions{
|
||||
Directory: path.Join(setting.StaticRootPath, "templates"),
|
||||
AppendDirectories: []string{path.Join(setting.CustomPath, "templates")},
|
||||
Directory: filepath.Join(conf.WorkDir(), "templates"),
|
||||
AppendDirectories: []string{filepath.Join(conf.CustomDir(), "templates")},
|
||||
Funcs: template.FuncMap(),
|
||||
IndentJSON: macaron.Env != macaron.PROD,
|
||||
}
|
||||
if !setting.LoadAssetsFromDisk {
|
||||
if !conf.Server.LoadAssetsFromDisk {
|
||||
renderOpt.TemplateFileSystem = templates.NewTemplateFileSystem("", renderOpt.AppendDirectories[0])
|
||||
}
|
||||
m.Use(macaron.Renderer(renderOpt))
|
||||
@@ -121,34 +120,34 @@ func newMacaron() *macaron.Macaron {
|
||||
if err != nil {
|
||||
log.Fatal("Failed to list locale files: %v", err)
|
||||
}
|
||||
localFiles := make(map[string][]byte)
|
||||
localeFiles := make(map[string][]byte)
|
||||
for _, name := range localeNames {
|
||||
localFiles[name] = conf.MustAsset("conf/locale/" + name)
|
||||
localeFiles[name] = conf.MustAsset("conf/locale/" + name)
|
||||
}
|
||||
m.Use(i18n.I18n(i18n.Options{
|
||||
SubURL: setting.AppSubURL,
|
||||
Files: localFiles,
|
||||
CustomDirectory: path.Join(setting.CustomPath, "conf/locale"),
|
||||
Langs: setting.Langs,
|
||||
Names: setting.Names,
|
||||
SubURL: conf.Server.Subpath,
|
||||
Files: localeFiles,
|
||||
CustomDirectory: filepath.Join(conf.CustomDir(), "conf", "locale"),
|
||||
Langs: conf.Langs,
|
||||
Names: conf.Names,
|
||||
DefaultLang: "en-US",
|
||||
Redirect: true,
|
||||
}))
|
||||
m.Use(cache.Cacher(cache.Options{
|
||||
Adapter: setting.CacheAdapter,
|
||||
AdapterConfig: setting.CacheConn,
|
||||
Interval: setting.CacheInterval,
|
||||
Adapter: conf.CacheAdapter,
|
||||
AdapterConfig: conf.CacheConn,
|
||||
Interval: conf.CacheInterval,
|
||||
}))
|
||||
m.Use(captcha.Captchaer(captcha.Options{
|
||||
SubURL: setting.AppSubURL,
|
||||
SubURL: conf.Server.Subpath,
|
||||
}))
|
||||
m.Use(session.Sessioner(setting.SessionConfig))
|
||||
m.Use(session.Sessioner(conf.SessionConfig))
|
||||
m.Use(csrf.Csrfer(csrf.Options{
|
||||
Secret: setting.SecretKey,
|
||||
Cookie: setting.CSRFCookieName,
|
||||
Secret: conf.SecretKey,
|
||||
Cookie: conf.CSRFCookieName,
|
||||
SetCookie: true,
|
||||
Header: "X-Csrf-Token",
|
||||
CookiePath: setting.AppSubURL,
|
||||
CookiePath: conf.Server.Subpath,
|
||||
}))
|
||||
m.Use(toolbox.Toolboxer(m, toolbox.Options{
|
||||
HealthCheckFuncs: []*toolbox.HealthCheckFuncDesc{
|
||||
@@ -163,15 +162,15 @@ func newMacaron() *macaron.Macaron {
|
||||
}
|
||||
|
||||
func runWeb(c *cli.Context) error {
|
||||
if c.IsSet("config") {
|
||||
setting.CustomConf = c.String("config")
|
||||
err := route.GlobalInit(c.String("config"))
|
||||
if err != nil {
|
||||
log.Fatal("Failed to initialize application: %v", err)
|
||||
}
|
||||
route.GlobalInit()
|
||||
|
||||
m := newMacaron()
|
||||
|
||||
reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
|
||||
ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
|
||||
ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: conf.Service.RequireSignInView})
|
||||
ignSignInAndCsrf := context.Toggle(&context.ToggleOptions{DisableCSRF: true})
|
||||
reqSignOut := context.Toggle(&context.ToggleOptions{SignOutRequired: true})
|
||||
|
||||
@@ -185,7 +184,7 @@ func runWeb(c *cli.Context) error {
|
||||
m.Get("/", ignSignIn, route.Home)
|
||||
m.Group("/explore", func() {
|
||||
m.Get("", func(c *context.Context) {
|
||||
c.Redirect(setting.AppSubURL + "/explore/repos")
|
||||
c.Redirect(conf.Server.Subpath + "/explore/repos")
|
||||
})
|
||||
m.Get("/repos", route.ExploreRepos)
|
||||
m.Get("/users", route.ExploreUsers)
|
||||
@@ -570,7 +569,7 @@ func runWeb(c *cli.Context) error {
|
||||
m.Post("/upload-file", repo.UploadFileToServer)
|
||||
m.Post("/upload-remove", bindIgnErr(form.RemoveUploadFile{}), repo.RemoveUploadFileFromServer)
|
||||
}, func(c *context.Context) {
|
||||
if !setting.Repository.Upload.Enabled {
|
||||
if !conf.Repository.Upload.Enabled {
|
||||
c.NotFound()
|
||||
return
|
||||
}
|
||||
@@ -658,21 +657,21 @@ func runWeb(c *cli.Context) error {
|
||||
}, ignSignIn)
|
||||
|
||||
m.Group("/-", func() {
|
||||
if setting.Prometheus.Enabled {
|
||||
if conf.Prometheus.Enabled {
|
||||
m.Get("/metrics", func(c *context.Context) {
|
||||
if !setting.Prometheus.EnableBasicAuth {
|
||||
if !conf.Prometheus.EnableBasicAuth {
|
||||
return
|
||||
}
|
||||
|
||||
c.RequireBasicAuth(setting.Prometheus.BasicAuthUsername, setting.Prometheus.BasicAuthPassword)
|
||||
c.RequireBasicAuth(conf.Prometheus.BasicAuthUsername, conf.Prometheus.BasicAuthPassword)
|
||||
}, promhttp.Handler())
|
||||
}
|
||||
})
|
||||
|
||||
// robots.txt
|
||||
m.Get("/robots.txt", func(c *context.Context) {
|
||||
if setting.HasRobotsTxt {
|
||||
c.ServeFileContent(path.Join(setting.CustomPath, "robots.txt"))
|
||||
if conf.HasRobotsTxt {
|
||||
c.ServeFileContent(filepath.Join(conf.CustomDir(), "robots.txt"))
|
||||
} else {
|
||||
c.NotFound()
|
||||
}
|
||||
@@ -683,69 +682,76 @@ func runWeb(c *cli.Context) error {
|
||||
|
||||
// Flag for port number in case first time run conflict.
|
||||
if c.IsSet("port") {
|
||||
setting.AppURL = strings.Replace(setting.AppURL, setting.HTTPPort, c.String("port"), 1)
|
||||
setting.HTTPPort = c.String("port")
|
||||
conf.Server.URL.Host = strings.Replace(conf.Server.URL.Host, conf.Server.URL.Port(), c.String("port"), 1)
|
||||
conf.Server.ExternalURL = conf.Server.URL.String()
|
||||
conf.Server.HTTPPort = c.String("port")
|
||||
}
|
||||
|
||||
var listenAddr string
|
||||
if setting.Protocol == setting.SCHEME_UNIX_SOCKET {
|
||||
listenAddr = fmt.Sprintf("%s", setting.HTTPAddr)
|
||||
if conf.Server.Protocol == "unix" {
|
||||
listenAddr = conf.Server.HTTPAddr
|
||||
} else {
|
||||
listenAddr = fmt.Sprintf("%s:%s", setting.HTTPAddr, setting.HTTPPort)
|
||||
listenAddr = fmt.Sprintf("%s:%s", conf.Server.HTTPAddr, conf.Server.HTTPPort)
|
||||
}
|
||||
log.Info("Listen on %v://%s%s", setting.Protocol, listenAddr, setting.AppSubURL)
|
||||
log.Info("Listen on %v://%s%s", conf.Server.Protocol, listenAddr, conf.Server.Subpath)
|
||||
|
||||
var err error
|
||||
switch setting.Protocol {
|
||||
case setting.SCHEME_HTTP:
|
||||
switch conf.Server.Protocol {
|
||||
case "http":
|
||||
err = http.ListenAndServe(listenAddr, m)
|
||||
case setting.SCHEME_HTTPS:
|
||||
var tlsMinVersion uint16
|
||||
switch setting.TLSMinVersion {
|
||||
case "SSL30":
|
||||
tlsMinVersion = tls.VersionSSL30
|
||||
|
||||
case "https":
|
||||
tlsMinVersion := tls.VersionTLS12
|
||||
switch conf.Server.TLSMinVersion {
|
||||
case "TLS13":
|
||||
tlsMinVersion = tls.VersionTLS13
|
||||
case "TLS12":
|
||||
tlsMinVersion = tls.VersionTLS12
|
||||
case "TLS11":
|
||||
tlsMinVersion = tls.VersionTLS11
|
||||
case "TLS10":
|
||||
fallthrough
|
||||
default:
|
||||
tlsMinVersion = tls.VersionTLS10
|
||||
}
|
||||
server := &http.Server{Addr: listenAddr, TLSConfig: &tls.Config{
|
||||
MinVersion: tlsMinVersion,
|
||||
CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256, tls.CurveP384, tls.CurveP521},
|
||||
PreferServerCipherSuites: true,
|
||||
CipherSuites: []uint16{
|
||||
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
|
||||
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
|
||||
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
|
||||
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
|
||||
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
|
||||
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
|
||||
},
|
||||
}, Handler: m}
|
||||
err = server.ListenAndServeTLS(setting.CertFile, setting.KeyFile)
|
||||
case setting.SCHEME_FCGI:
|
||||
server := &http.Server{
|
||||
Addr: listenAddr,
|
||||
TLSConfig: &tls.Config{
|
||||
MinVersion: uint16(tlsMinVersion),
|
||||
CurvePreferences: []tls.CurveID{tls.X25519, tls.CurveP256, tls.CurveP384, tls.CurveP521},
|
||||
PreferServerCipherSuites: true,
|
||||
CipherSuites: []uint16{
|
||||
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
|
||||
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
|
||||
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
|
||||
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
|
||||
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
|
||||
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
|
||||
},
|
||||
}, Handler: m}
|
||||
err = server.ListenAndServeTLS(conf.Server.CertFile, conf.Server.KeyFile)
|
||||
|
||||
case "fcgi":
|
||||
err = fcgi.Serve(nil, m)
|
||||
case setting.SCHEME_UNIX_SOCKET:
|
||||
os.Remove(listenAddr)
|
||||
|
||||
case "unix":
|
||||
err = os.Remove(listenAddr)
|
||||
if err != nil {
|
||||
log.Fatal("Failed to remove existing Unix domain socket: %v", err)
|
||||
}
|
||||
|
||||
var listener *net.UnixListener
|
||||
listener, err = net.ListenUnix("unix", &net.UnixAddr{listenAddr, "unix"})
|
||||
listener, err = net.ListenUnix("unix", &net.UnixAddr{Name: listenAddr, Net: "unix"})
|
||||
if err != nil {
|
||||
break // Handle error after switch
|
||||
log.Fatal("Failed to listen on Unix networks: %v", err)
|
||||
}
|
||||
|
||||
// FIXME: add proper implementation of signal capture on all protocols
|
||||
// execute this on SIGTERM or SIGINT: listener.Close()
|
||||
if err = os.Chmod(listenAddr, os.FileMode(setting.UnixSocketPermission)); err != nil {
|
||||
log.Fatal("Failed to set permission of unix socket: %v", err)
|
||||
if err = os.Chmod(listenAddr, conf.Server.UnixSocketMode); err != nil {
|
||||
log.Fatal("Failed to change permission of Unix domain socket: %v", err)
|
||||
}
|
||||
err = http.Serve(listener, m)
|
||||
|
||||
default:
|
||||
log.Fatal("Invalid protocol: %s", setting.Protocol)
|
||||
log.Fatal("Unexpected server protocol: %s", conf.Server.Protocol)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
|
||||
Reference in New Issue
Block a user