func Index(l *log.Logger, r render.Render, level *leveldb.DB) { // Message All var response ResponseData var readOpts db.ReadOptions keys, err := level.Get([]byte("keys"), &readOpts) if err == nil { keyList := strings.Split(string(keys), ",") response.Msg = "データベースのデータ" datas := make([]Message, len(keyList)) for idx, key := range keyList { data, _ := level.Get([]byte(key), &readOpts) var message Message err := json.Unmarshal(data, &message) if err != nil { panic(err) } l.Println(key, message) datas[idx] = message } response.Datas = datas } else { // not database recodes response.Msg = "データベースのサンプル" response.Datas = []Message{ {1, "ほげ", "*****@*****.**", "ふがふが", time.Now()}, {2, "ねぷねぷ", "*****@*****.**", "ねぷてぬ", time.Now()}, } } r.HTML(200, "index", response) }
func Create(ms Message, level *leveldb.DB) (int, string) { // input Message inputData := ms inputData.PostData = time.Now() if inputData.Name == "" || inputData.Message == "" { return 400, "error" } var readOpts db.ReadOptions // inputData toJson inputJsonData, err := json.Marshal(inputData) if err != nil { panic(err) } // inputData save var writeOpts db.WriteOptions err = level.Set([]byte(inputData.Name), inputJsonData, &writeOpts) if err != nil { panic(err) } // find keys var lastedKeys string keys, err := level.Get([]byte("keys"), &readOpts) if err == nil { lastedKeys = string(keys) lastedKeys += "," } else { lastedKeys = "" } // update keys lastedKeys += inputData.Name err = level.Set([]byte("keys"), []byte(lastedKeys), &writeOpts) if err != nil { panic(err) } return 200, "ok" }