summaryrefslogtreecommitdiff
path: root/main.go
blob: dcb7d4748ba91a92291ab63a7f715f60e6b10190 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
package main

import (
    "net/http"
    "flag"
    "fmt"
    "strings"
    "crypto/md5"
    "encoding/json"
    "os"
    "html/template"
    "log"
    "path"

    _"github.com/lib/pq"
    "github.com/jmoiron/sqlx"
)

type Config struct {
    Listen   string `json:"listen"`
    DBStr    string `json:"db"`
    TmplPath string `json:"tmpl"`
}

type Server struct {
    mux  *http.ServeMux
    conf *Config
    db   *sqlx.DB
}

type note struct {
    Hash     string
    Name     string
    Location string
}

const scheme = `
    CREATE TABLE IF NOT EXISTS notes (
        hash     VARCHAR(4) PRIMARY KEY,
        name     TEXT NOT NULL,
        location TEXT NOT NULL,
        available BOOL DEFAULT True
    )
`

func main() {
    confFlag := flag.String("c", "config.json", "config file")
    flag.Parse()

    f, err := os.Open(*confFlag)
    if err != nil {
        log.Fatal(err)
    }

    var conf Config
    err = json.NewDecoder(f).Decode(&conf)
    if err != nil {
        log.Fatal(err)
    }

    s := NewServer(&conf)
    if err != nil {
        log.Fatal(err)
    }

    err = s.Connect()
    if err != nil {
        log.Fatal(err)
    }

    log.Fatal(s.Run())
}

func NewServer(conf *Config) *Server {
    s := &Server{}
    s.mux = http.NewServeMux()
    s.mux.HandleFunc("/", s.httpRoot)
    s.conf = conf

    return s
}

func (s *Server) Connect() error {
    var err error
    s.db, err = sqlx.Connect("postgres", s.conf.DBStr)
    if err != nil {
        return err
    }

    s.db.MustExec(scheme)
    return nil
}

func (s *Server) Run() error {
    log.Printf("Listening on %s", s.conf.Listen)
    return http.ListenAndServe(s.conf.Listen, s.mux)
}

func (s *Server) renderTemplate(w http.ResponseWriter, data interface{}, pathname string) error {

    tmpl, err := template.ParseFiles(path.Join(s.conf.TmplPath, pathname))
    if err != nil {
        log.Print(err)
        return err
    }

    err = tmpl.Execute(w, data)
    if err != nil {
        log.Print(err)
    }
    return err
}

func (s *Server) httpCreateNode(w http.ResponseWriter, r *http.Request) {
    var (
        name = r.FormValue("name")
        location = r.FormValue("location")
    )

    hash := fmt.Sprintf("%x", md5.Sum([]byte(name)))[0:4]

    _, err := s.db.ExecContext(r.Context(), `
        INSERT INTO notes (hash, name, location)
        VALUES ($1, $2, $3)`, hash, name, location)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    var ref strings.Builder
    fmt.Fprintf(&ref, "#%s", hash)
    if location != "" {
        fmt.Fprintf(&ref, "/%s", location)
    }

    fmt.Fprintf(w, `
    <html>
        <p><b>Note:</b> %s</p>
        <p><b>Location:</b> %s</p>
        <p><b>Hash:</b> %s"</p>
        <p><b>Ref:</b> %s</p>
    </html>`, name, location, hash, ref.String())
}

func (s *Server) httpRoot(w http.ResponseWriter, r *http.Request) {
    if r.URL.Path != "/" {
        w.WriteHeader(http.StatusNotFound)
        return
    }

    if r.Method == "POST" {
        s.httpCreateNode(w, r)
        return
    }

    var page struct {
        Notes []note
        Msg string
    }

    err := s.db.SelectContext(r.Context(), &page.Notes, `
        SELECT hash, name, location FROM notes WHERE available = True`)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    s.renderTemplate(w, &page, "root.template")
}