Skip to content
Draft
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
6 changes: 6 additions & 0 deletions configs/configs.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io"
"os"
"path/filepath"
"sync"
"time"

"github.com/xinliangnote/go-gin-api/pkg/env"
Expand All @@ -16,6 +17,7 @@ import (
)

var config = new(Config)
var configLock sync.RWMutex

type Config struct {
MySQL struct {
Expand Down Expand Up @@ -128,12 +130,16 @@ func init() {

viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
configLock.Lock()
defer configLock.Unlock()
if err := viper.Unmarshal(config); err != nil {
panic(err)
}
})
}

func Get() Config {
configLock.RLock()
defer configLock.RUnlock()
return *config
}
32 changes: 32 additions & 0 deletions configs/configs_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
package configs

import (
"testing"

"github.com/spf13/viper"
)

func TestRace(t *testing.T) {
done := make(chan bool)

go func() {
for i := 0; i < 100; i++ {
Get()
}
done <- true
}()

go func() {
for i := 0; i < 100; i++ {
configLock.Lock()
if err := viper.Unmarshal(config); err != nil {
// ignore error
}
configLock.Unlock()
}
done <- true
}()

<-done
<-done
}
2 changes: 2 additions & 0 deletions pkg/env/env.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package env
import (
"flag"
"fmt"
"os"
"strings"
)

Expand Down Expand Up @@ -53,6 +54,7 @@ func (e *environment) IsPro() bool {
func (e *environment) t() {}

func init() {
flag.CommandLine.Init(os.Args[0], flag.ContinueOnError)
env := flag.String("env", "", "请输入运行环境:\n dev:开发环境\n fat:测试环境\n uat:预上线环境\n pro:正式环境\n")
flag.Parse()

Expand Down