Save/load profile

master
Michael Dvorkin 12 years ago
parent 327c3e256d
commit 713b87609d
  1. 37
      js.go
  2. 50
      lib/profile.go

37
js.go

@ -0,0 +1,37 @@
// Copyright (c) 2013 by Michael Dvorkin. All Rights Reserved.
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
package main
import (
"fmt"
"encoding/json"
)
type Config struct {
MarketRefreshRate int
QuotesRefreshRate int
Tickers []string
SortBy string
SortOrder string
}
func main() {
var cfg Config
cfg.MarketRefreshRate = 1
cfg.QuotesRefreshRate = 1
cfg.Tickers = []string{ "AAPL", "ALU", "HPQ", "IBM" }
cfg.SortBy = "Ticker"
cfg.SortOrder = "Desc"
fmt.Printf("%+v\n", cfg)
blob, err := json.Marshal(cfg)
if err != nil {
panic(err)
}
fmt.Printf("%q\n", blob)
var cfg2 Config
err = json.Unmarshal(blob, &cfg2)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", cfg2)
}

@ -1,8 +1,56 @@
// Copyright (c) 2013 by Michael Dvorkin. All Rights Reserved.
//=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
package mop
import (
"strings"
"os/user"
"io/ioutil"
"encoding/json"
)
const rcfile = "/.moprc"
type Profile struct {
MarketRefreshRate int
QuotesRefreshRate int
Tickers []string
SortBy string
SortOrder string
}
var profile Profile
//-----------------------------------------------------------------------------
func LoadProfile() string {
return "AAPL+ALU+ATVI+C+COH+GOOG+HPQ+IBM+MA+TSLA+V+YHOO+ININ+CRM+SAAS"
data, err := ioutil.ReadFile(defaultProfile())
if err != nil {
// Set default values.
profile.MarketRefreshRate = 12
profile.QuotesRefreshRate = 5
profile.Tickers = []string{ "AAPL", "C", "GOOG", "IBM", "KO", "ORCL", "V" }
profile.SortBy = "Ticker"
profile.SortOrder = "Desc"
profile.Save()
} else {
json.Unmarshal(data, &profile)
}
return strings.Join(profile.Tickers, "+")
}
//-----------------------------------------------------------------------------
func (profile *Profile) Save() error {
if data, err := json.Marshal(profile); err != nil {
return err
} else {
return ioutil.WriteFile(defaultProfile(), data, 0644)
}
}
//-----------------------------------------------------------------------------
func defaultProfile() string {
usr, err := user.Current()
if err != nil {
panic(err)
}
return usr.HomeDir + rcfile
}

Loading…
Cancel
Save