package main import ( "flag" "fmt" "log" "net/http" "os" "git.tilde.town/tildetown/bbj2/server/cmd/api" "git.tilde.town/tildetown/bbj2/server/cmd/config" "git.tilde.town/tildetown/bbj2/server/cmd/db" _ "github.com/mattn/go-sqlite3" ) // TODO tests func main() { var configFlag = flag.String("config", "config.yml", "A path to a config file.") var resetFlag = flag.Bool("reset", false, "reset the database. WARNING this wipes everything.") flag.Parse() logger := log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lshortfile) opts := &config.Options{ ConfigPath: *configFlag, Reset: *resetFlag, Logger: logger, } err := _main(opts) if err != nil { logger.Fatalln(err.Error()) } } /* TODO my next initiative is doing /something/ about the database layer. The amount of boiler plate involved in: - prepare a statement - prepare a result struct - execute statement - scan into result is wild; the error handling is really out of control. I need to think of abstractions for this. The "easiest" is just making blunt, non performant functions that return structs and a single error, but that could get out of control too. In general I think not having raw sql ever in application code is a good place to start. */ func _main(opts *config.Options) error { cfg, err := config.ParseConfig(opts.ConfigPath) if err != nil { return fmt.Errorf("could not read config file '%s'", opts.ConfigPath) } opts.Config = *cfg teardown, err := db.Setup(opts) if err != nil { return fmt.Errorf("could not initialize DB: %w", err) } defer teardown() err = db.EnsureSchema(*opts) if err != nil { return err } setupAPI(*opts) // TODO TLS or SSL or something opts.Logger.Printf("starting server at %s:%d", cfg.Host, cfg.Port) if err := http.ListenAndServe(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port), nil); err != nil { return fmt.Errorf("http server exited with error: %w", err) } return nil } func setupAPI(opts config.Options) { a := api.NewAPI(opts) http.HandleFunc("/instance_info", func(w http.ResponseWriter, req *http.Request) { a.Invoke(w, req, a.InstanceInfo) }) http.HandleFunc("/user_register", func(w http.ResponseWriter, req *http.Request) { a.Invoke(w, req, a.UserRegister) }) http.HandleFunc("/check_auth", func(w http.ResponseWriter, req *http.Request) { a.Invoke(w, req, a.CheckAuth) }) } /* http.HandleFunc("/thread_index", handler(opts, func(w http.ResponseWriter, req *http.Request) { db := opts.DB rows, err := db.Query("SELECT * FROM threads JOIN messages ON threads.thread_id = messages.thread_id") if err != nil { serverErr(w, err) return } defer rows.Close() for rows.Next() { var id string err = rows.Scan(&id) if err != nil { serverErr(w, err) return } opts.Log(id) } writeResponse(w, BBJResponse{Data: "TODO"}) // TODO })) http.HandleFunc("/thread_create", handler(opts, func(w http.ResponseWriter, req *http.Request) { if req.Method != "POST" { badMethod(w) return } // TODO make this getUserInfoFromReq or similar so we can use the user ID later user, err := getUserFromReq(opts, req) if err != nil { writeErrorResponse(w, 403, BBJResponse{ Error: true, Data: err.Error(), }) return } type threadCreateArgs struct { Title string Body string SendRaw bool `json:"send_raw"` } var args threadCreateArgs if err := json.NewDecoder(req.Body).Decode(&args); err != nil { invalidArgs(w) return } if args.Title == "" || args.Body == "" { invalidArgs(w) return } db := opts.DB tx, err := db.Begin() if err != nil { serverErr(w, err) return } stmt, err := tx.Prepare("insert into threads VALUES ( ?, ?, ?, ?, ?, 0, 0, ? )") if err != nil { serverErr(w, err) return } defer stmt.Close() threadID, err := uuid.NewRandom() if err != nil { serverErr(w, err) return } now := time.Now() if _, err = stmt.Exec( threadID, user.ID, args.Title, now, now, user.Username, ); err != nil { serverErr(w, err) return } stmt, err = tx.Prepare("insert into messages values ( ?, 1, ?, ?, 0, ?, ? )") if err != nil { serverErr(w, err) return } defer stmt.Close() if _, err = stmt.Exec( threadID, user.ID, now, args.Body, args.SendRaw, ); err != nil { serverErr(w, err) return } if err = tx.Commit(); err != nil { serverErr(w, err) return } stmt, err = db.Prepare("select * from threads where thread_id = ? limit 1") if err != nil { serverErr(w, err) return } defer stmt.Close() t := &Thread{} // TODO fill in rest of thread if err = stmt.QueryRow(threadID).Scan( t.ID, t.Author, t.Title, t.LastMod, t.Created, t.ReplyCount, t.Pinned, t.LastAuthor, ); err != nil { serverErr(w, err) return } stmt, err = db.Prepare("select * from messages where thread_id = ?") if err != nil { serverErr(w, err) return } defer stmt.Close() rows, err := stmt.Query(threadID) if err != nil { serverErr(w, err) return } t.Messages = []Message{} for rows.Next() { m := &Message{} if err := rows.Scan( m.ThreadID, m.PostID, m.Author, m.Created, m.Edited, m.Body, m.SendRaw, ); err != nil { serverErr(w, err) return } t.Messages = append(t.Messages, *m) } writeResponse(w, BBJResponse{Data: t}) })) */