Last active
June 28, 2021 11:23
-
-
Save yutakahashi114/76c063408fc8a79ebe643df9ad39214a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"encoding/json" | |
"fmt" | |
"sync" | |
) | |
const poolFileName = "pool.json" | |
func main() { | |
data, err := ioutil.ReadFile(poolFileName) | |
if err != nil { | |
panic(err) | |
} | |
poolMap := make(map[UserPoolID]UserMap) | |
err = json.Unmarshal(data, &poolMap) | |
if err != nil { | |
panic(err) | |
} | |
userPool = UserPool{ | |
poolMap: poolMap, | |
mutex: &sync.Mutex{}, | |
} | |
... | |
} | |
type User struct { | |
UUID string `json:"uuid"` | |
Password string `json:"password"` | |
Username Username `json:"username"` | |
Email string `json:"email"` | |
EmailVerified bool `json:"email_verified"` | |
} | |
type Username string | |
type UserMap map[Username]*User | |
type UserPoolID string | |
type UserPool struct { | |
poolMap map[UserPoolID]UserMap | |
mutex *sync.Mutex | |
} | |
func (pool UserPool) GetUser(userPoolID UserPoolID, username Username) (*User, bool) { | |
pool.mutex.Lock() | |
defer pool.mutex.Unlock() | |
return pool.getUser(userPoolID, username) | |
} | |
func (pool UserPool) getUser(userPoolID UserPoolID, username Username) (*User, bool) { | |
uMap, ok := pool.poolMap[userPoolID] | |
if !ok { | |
return nil, false | |
} | |
u, ok := uMap[username] | |
if !ok { | |
return nil, false | |
} | |
return u, true | |
} | |
func (pool UserPool) CreateUser(userPoolID UserPoolID, user User) error { | |
pool.mutex.Lock() | |
defer pool.mutex.Unlock() | |
uMap, ok := pool.poolMap[userPoolID] | |
if !ok { | |
uMap = make(UserMap) | |
pool.poolMap[userPoolID] = uMap | |
} | |
if _, ok := uMap[user.Username]; ok { | |
return fmt.Errorf("already exist") | |
} | |
uMap[user.Username] = &user | |
return pool.updateFile() | |
} | |
func (pool UserPool) updateFile() error { | |
file, err := os.Create(poolFileName) | |
if err != nil { | |
return err | |
} | |
defer file.Close() | |
content, err := json.Marshal(pool.poolMap) | |
if err != nil { | |
return err | |
} | |
_, err = file.Write(content) | |
return err | |
} | |
func (pool UserPool) DeleteUser(userPoolID UserPoolID, username Username) error { | |
pool.mutex.Lock() | |
defer pool.mutex.Unlock() | |
if _, exist := pool.getUser(userPoolID, username); exist { | |
delete(pool.poolMap[userPoolID], username) | |
} | |
return pool.updateFile() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment