via

Simple pubsub server inspired by https://patchbay.pub/
git clone https://git.ce9e.org/via.git

commit
dc3496d3be293eaa6c38e448141950c457cb9b06
parent
6f19bac953b4b59a64922bb1d69120d822f0fa59
Author
Tobias Bengfort <tobias.bengfort@posteo.de>
Date
2020-10-15 07:55
store history in files

Diffstat

M via.go 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++

1 files changed, 52 insertions, 0 deletions


diff --git a/via.go b/via.go

@@ -2,6 +2,7 @@ package main
    2     2 
    3     3 import (
    4     4 	"encoding/base64"
   -1     5 	"encoding/json"
    5     6 	"flag"
    6     7 	"fmt"
    7     8 	"io/ioutil"
@@ -49,6 +50,50 @@ func getStorePath(key string) string {
   49    50 	return path.Join(dir, hash)
   50    51 }
   51    52 
   -1    53 func (topic Topic) storeHistory(key string) {
   -1    54 	topic.Lock()
   -1    55 	defer topic.Unlock()
   -1    56 
   -1    57 	path := getStorePath(fmt.Sprintf("%s:%s", key, topic.password))
   -1    58 
   -1    59 	content, err := json.Marshal(topic.history)
   -1    60 	if err != nil {
   -1    61 		log.Println("error storing history:", err)
   -1    62 		return
   -1    63 	}
   -1    64 
   -1    65 	err = ioutil.WriteFile(path, content, 0644)
   -1    66 	if err != nil {
   -1    67 		log.Println("error storing history:", err)
   -1    68 		return
   -1    69 	}
   -1    70 }
   -1    71 
   -1    72 func (topic *Topic) restoreHistory(key string) {
   -1    73 	topic.Lock()
   -1    74 	defer topic.Unlock()
   -1    75 
   -1    76 	path := getStorePath(fmt.Sprintf("%s:%s", key, topic.password))
   -1    77 
   -1    78 	content, err := ioutil.ReadFile(path)
   -1    79 	if err != nil {
   -1    80 		log.Println("error restoring history:", err)
   -1    81 		return
   -1    82 	}
   -1    83 
   -1    84 	var history []Msg
   -1    85 	err = json.Unmarshal(content, &history)
   -1    86 	if err != nil {
   -1    87 		log.Println("error restoring history:", err)
   -1    88 		return
   -1    89 	}
   -1    90 
   -1    91 	topic.history = history
   -1    92 	if len(history) > 0 {
   -1    93 		topic.lastId = history[len(history)-1].Id
   -1    94 	}
   -1    95 }
   -1    96 
   52    97 func (topic *Topic) post(data []byte) {
   53    98 	topic.Lock()
   54    99 	defer topic.Unlock()
@@ -84,6 +129,9 @@ func pushChannel(key string, password string, ch chan Msg, lastId int) bool {
   84   129 			history: make([]Msg, 0),
   85   130 			lastId: 0,
   86   131 		}
   -1   132 		if topic.hasHistory {
   -1   133 			topic.restoreHistory(key)
   -1   134 		}
   87   135 		mux.Lock()
   88   136 		topics[key] = topic
   89   137 		mux.Unlock()
@@ -151,6 +199,10 @@ func post(w http.ResponseWriter, r *http.Request) {
  151   199 	}
  152   200 
  153   201 	topic.post(body)
   -1   202 
   -1   203 	if topic.hasHistory {
   -1   204 		topic.storeHistory(key)
   -1   205 	}
  154   206 }
  155   207 
  156   208 func get(w http.ResponseWriter, r *http.Request) {