package main import ( "database/sql" "encoding/json" "fmt" "html/template" "log" "net/http" "os" _ "modernc.org/sqlite" ) type Config struct { Port uint } type user struct { id uint64 name string handle string pass string email string about string } type persona struct { id uint64 userid uint64 handle string name string about string colour string } type Post struct { Id uint64 Time uint Userid uint64 Personaid uint64 Text string PersonaName string UserName string PersonaHandle string UserHandle string } type comment struct { id uint64 time uint userid uint64 personaid uint64 postid uint64 text string } type page struct { Title string Posts []Post } var db *sql.DB func main() { var err error // Load config fmt.Println("Loading config.json") cfgfile, err := os.Open("config.json") if err != nil { log.Fatal("Error reading config.json!") return } defer cfgfile.Close() decoder := json.NewDecoder(cfgfile) Config := Config{} err = decoder.Decode(&Config) if err != nil { log.Fatal("Can't decode config.json!") return } db, err = sql.Open("sqlite", "database.db") if err != nil { log.Fatal(err) } fmt.Printf("Starting listener on :%v", Config.Port) http.Handle("/static/", http.FileServer(http.Dir("./"))) http.HandleFunc("/", httpRootHandler) err = http.ListenAndServe(fmt.Sprintf(":%v", Config.Port), nil) if err != nil { log.Fatal(err) } db.Close() } func httpRootHandler(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("index.html") posts, err := getPosts() if err != nil { log.Fatal(err) http.Error(w, http.StatusText(500), 500) return } var p page p.Title = "Snuffler" p.Posts = posts t.Execute(w, p) } func getPosts() ([]Post, error) { rows, err := db.Query("SELECT post.id, post.time, post.userid, post.personaid, post.text, user.name, user.handle, persona.name, persona.handle FROM posts AS post LEFT JOIN users AS user ON post.userid=user.id LEFT JOIN personas AS persona ON post.personaid=persona.id") if err != nil { log.Fatal(err) return nil, err } var posts []Post for rows.Next() { var post Post err := rows.Scan(&post.Id, &post.Time, &post.Userid, &post.Personaid, &post.Text, &post.UserName, &post.UserHandle, &post.PersonaName, &post.PersonaHandle) if err != nil { log.Fatal(err) return nil, err } posts = append(posts, post) } err = rows.Err() if err != nil { log.Fatal(err) return nil, err } return posts, nil }