2024-12-27 15:05:42 +02:00
package main
import (
"database/sql"
2024-12-28 00:57:15 +02:00
"encoding/json"
"fmt"
2024-12-27 15:05:42 +02:00
"html/template"
"log"
"net/http"
2024-12-28 00:57:15 +02:00
"os"
2024-12-27 15:05:42 +02:00
_ "modernc.org/sqlite"
)
2024-12-28 00:57:15 +02:00
type Config struct {
Port uint
}
2024-12-27 15:05:42 +02:00
type user struct {
id uint
name string
handle string
pass string
email string
about string
}
type persona struct {
id uint
userid uint
handle string
name string
about string
colour string
}
type Post struct {
Id uint
Time uint
Userid uint
Personaid uint
Text string
PersonaName string
UserName string
PersonaHandle string
UserHandle string
}
type comment struct {
id uint
time uint
userid uint
personaid uint
postid uint
text string
}
type page struct {
Title string
Posts [ ] Post
}
var db * sql . DB
func main ( ) {
var err error
2024-12-28 00:57:15 +02:00
// 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
}
2024-12-27 15:05:42 +02:00
db , err = sql . Open ( "sqlite" , "database.db" )
if err != nil {
log . Fatal ( err )
}
2024-12-28 00:57:15 +02:00
fmt . Printf ( "Starting listener on :%v" , Config . Port )
2024-12-27 15:05:42 +02:00
http . Handle ( "/static/" , http . FileServer ( http . Dir ( "./" ) ) )
http . HandleFunc ( "/" , httpRootHandler )
2024-12-28 00:57:15 +02:00
err = http . ListenAndServe ( fmt . Sprintf ( ":%v" , Config . Port ) , nil )
2024-12-27 15:05:42 +02:00
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
}