Moved the API and Report routes to the router generator route list.

Tweaked the code to make it more flexible.
This commit is contained in:
Azareal 2017-05-02 18:24:33 +01:00
parent 001b51624b
commit cac3ffe982
8 changed files with 73 additions and 59 deletions

View File

@ -50,6 +50,9 @@ func (router *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
//fmt.Println("req.URL.Path:",req.URL.Path)
//fmt.Println("extra_data:",extra_data)
switch(prefix) {
case "/api":
route_api(w,req)
return
case "/static":
req.URL.Path += extra_data
route_static(w,req)
@ -63,6 +66,12 @@ func (router *GenRouter) ServeHTTP(w http.ResponseWriter, req *http.Request) {
case "/forum":
route_forum(w,req,extra_data)
return
case "/report":
switch(req.URL.Path) {
case "/report/submit/":
route_report_submit(w,req,extra_data)
return
}
case "/topics":
switch(req.URL.Path) {
case "/topics/create/":

14
main.go
View File

@ -96,7 +96,10 @@ func compile_templates() {
}
func write_template(name string, content string) {
write_file("./template_" + name + ".go", content)
err := write_file("./template_" + name + ".go", content)
if err != nil {
log.Fatal(err)
}
}
func init_templates() {
@ -164,8 +167,6 @@ func main(){
}
init_templates()
db.SetMaxOpenConns(64)
err = init_errors()
if err != nil {
log.Fatal(err)
@ -183,7 +184,6 @@ func main(){
external_sites["YT"] = "https://www.youtube.com/"
hooks["trow_assign"] = nil
hooks["rrow_assign"] = nil
init_plugins()
router := NewGenRouter(http.FileServer(http.Dir("./uploads")))
@ -201,7 +201,7 @@ func main(){
router.HandleFunc("/reply/edit/submit/", route_reply_edit_submit)
router.HandleFunc("/reply/delete/submit/", route_reply_delete_submit)
router.HandleFunc("/reply/like/submit/", route_reply_like_submit)
router.HandleFunc("/report/submit/", route_report_submit)
///router.HandleFunc("/report/submit/", route_report_submit)
router.HandleFunc("/topic/edit/submit/", route_edit_topic)
router.HandleFunc("/topic/delete/submit/", route_delete_topic)
router.HandleFunc("/topic/stick/submit/", route_stick_topic)
@ -265,9 +265,9 @@ func main(){
///router.HandleFunc("/panel/groups/edit/perms/submit/", route_panel_groups_edit_perms_submit)
///router.HandleFunc("/panel/groups/create/", route_panel_groups_create_submit)
///router.HandleFunc("/panel/logs/mod/", route_panel_logs_mod)
router.HandleFunc("/api/", route_api)
//router.HandleFunc("/exit/", route_exit)
///router.HandleFunc("/api/", route_api)
//router.HandleFunc("/exit/", route_exit)
///router.HandleFunc("/", default_route)
defer db.Close()

View File

@ -99,20 +99,25 @@ func init_database() (err error) {
if(dbpassword != ""){
dbpassword = ":" + dbpassword
}
// Open the database connection
db, err = sql.Open("mysql",dbuser + dbpassword + "@tcp(" + dbhost + ":" + dbport + ")/" + dbname + "?collation=" + db_collation)
if err != nil {
return err
}
// Make sure that the connection is alive..
// Make sure that the connection is alive
err = db.Ping()
if err != nil {
return err
}
// Getting the database version..
// Fetch the database version
db.QueryRow("SELECT VERSION()").Scan(&db_version)
// Set the number of max open connections
db.SetMaxOpenConns(64)
/*log.Print("Preparing get_session statement.")
get_session_stmt, err = db.Prepare("select `uid`,`name`,`group`,`is_super_admin`,`session`,`email`,`avatar`,`message`,`url_prefix`,`url_name`,`level`,`score`,`last_ip` from `users` where `uid` = ? and `session` = ? AND `session` <> ''")
if err != nil {

View File

@ -44,13 +44,12 @@ func (router *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
router.RLock()
handle, ok := router.routes[prefix]
if ok {
router.RUnlock()
if ok {
handle(w,req)
return
}
//fmt.Println(req.URL.Path[:strings.LastIndexByte(req.URL.Path,'/')])
router.RUnlock()
NotFound(w,req)
}

View File

@ -22,14 +22,19 @@ func addRouteGroup(path string, routes ...Route) {
func routes() {
//addRoute("default_route","","")
addRoute("route_api","/api/","")
addRoute("route_static","/static/","req.URL.Path += extra_data")
addRoute("route_overview","/overview/","")
//addRoute("route_custom_page","/pages/",""/*,"&extra_data"*/)
addRoute("route_forums","/forums/",""/*,"&forums"*/)
addRoute("route_forum","/forum/","","extra_data")
//addRoute("route_topic_create","/topics/create/","","extra_data")
//addRoute("route_topics","/topics/",""/*,"&groups","&forums"*/)
addRouteGroup("/report/",
Route{"route_report_submit","/report/submit/","",[]string{"extra_data"}},
)
addRouteGroup("/topics/",
Route{"route_topics","/topics/","",[]string{}},
Route{"route_topic_create","/topics/create/","",[]string{"extra_data"}},

View File

@ -984,7 +984,7 @@ func route_profile_reply_create(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/user/" + strconv.Itoa(uid), http.StatusSeeOther)
}
func route_report_submit(w http.ResponseWriter, r *http.Request) {
func route_report_submit(w http.ResponseWriter, r *http.Request, sitem_id string) {
user, ok := SimpleSessionCheck(w,r)
if !ok {
return
@ -1008,7 +1008,7 @@ func route_report_submit(w http.ResponseWriter, r *http.Request) {
return
}
item_id, err := strconv.Atoi(r.URL.Path[len("/report/submit/"):])
item_id, err := strconv.Atoi(sitem_id)
if err != nil {
LocalError("Bad ID",w,r,user)
return
@ -1016,11 +1016,9 @@ func route_report_submit(w http.ResponseWriter, r *http.Request) {
item_type := r.FormValue("type")
fid := 1
var fid int = 1
var tid int
var title string
var content string
var data string
var title, content, data string
if item_type == "reply" {
err = db.QueryRow("select tid, content from replies where rid = ?", item_id).Scan(&tid, &content)
if err == sql.ErrNoRows {

24
user.go
View File

@ -63,7 +63,7 @@ type StaticUserStore struct {
items map[int]*User
length int
capacity int
mu sync.RWMutex
sync.RWMutex
}
func NewStaticUserStore(capacity int) *StaticUserStore {
@ -71,9 +71,9 @@ func NewStaticUserStore(capacity int) *StaticUserStore {
}
func (sts *StaticUserStore) Get(id int) (*User, error) {
sts.mu.RLock()
sts.RLock()
item, ok := sts.items[id]
sts.mu.RUnlock()
sts.RUnlock()
if ok {
return item, nil
}
@ -89,9 +89,9 @@ func (sts *StaticUserStore) GetUnsafe(id int) (*User, error) {
}
func (sts *StaticUserStore) CascadeGet(id int) (*User, error) {
sts.mu.RLock()
sts.RLock()
user, ok := sts.items[id]
sts.mu.RUnlock()
sts.RUnlock()
if ok {
return user, nil
}
@ -136,18 +136,18 @@ func (sts *StaticUserStore) Load(id int) error {
}
func (sts *StaticUserStore) Set(item *User) error {
sts.mu.Lock()
sts.Lock()
_, ok := sts.items[item.ID]
if ok {
sts.items[item.ID] = item
} else if sts.length >= sts.capacity {
sts.mu.Unlock()
sts.Unlock()
return ErrStoreCapacityOverflow
} else {
sts.items[item.ID] = item
sts.length++
}
sts.mu.Unlock()
sts.Unlock()
return nil
}
@ -155,9 +155,9 @@ func (sts *StaticUserStore) Add(item *User) error {
if sts.length >= sts.capacity {
return ErrStoreCapacityOverflow
}
sts.mu.Lock()
sts.Lock()
sts.items[item.ID] = item
sts.mu.Unlock()
sts.Unlock()
sts.length++
return nil
}
@ -172,9 +172,9 @@ func (sts *StaticUserStore) AddUnsafe(item *User) error {
}
func (sts *StaticUserStore) Remove(id int) error {
sts.mu.Lock()
sts.Lock()
delete(sts.items,id)
sts.mu.Unlock()
sts.Unlock()
sts.length--
return nil
}

View File

@ -1,5 +1,5 @@
package main
import "log"
import "fmt"
import "time"
import "os"
@ -66,7 +66,7 @@ func relative_time(in string) (string, error) {
}
}
func SendEmail(email string, subject string, msg string) bool {
func SendEmail(email string, subject string, msg string) (res bool) {
// This hook is useful for plugin_sendmail or for testing tools. Possibly to hook it into some sort of mail server?
if vhooks["email_send_intercept"] != nil {
return vhooks["email_send_intercept"](email, subject, msg).(bool)
@ -75,57 +75,58 @@ func SendEmail(email string, subject string, msg string) bool {
con, err := smtp.Dial(smtp_server + ":" + smtp_port)
if err != nil {
return false
return
}
if smtp_username != "" {
auth := smtp.PlainAuth("",smtp_username,smtp_password,smtp_server)
err = con.Auth(auth)
if err != nil {
return false
return
}
}
err = con.Mail(site_email)
if err != nil {
return false
return
}
err = con.Rcpt(email)
if err != nil {
return false
return
}
email_data, err := con.Data()
if err != nil {
return false
return
}
_, err = fmt.Fprintf(email_data, body)
if err != nil {
return false
return
}
err = email_data.Close()
if err != nil {
return false
return
}
err = con.Quit()
if err != nil {
return false
return
}
return true
}
func write_file(name string, content string) {
func write_file(name string, content string) (err error) {
f, err := os.Create(name)
if err != nil {
log.Fatal(err)
return err
}
_, err = f.WriteString(content)
if err != nil {
log.Fatal(err)
return err
}
f.Sync()
f.Close()
return
}
func word_count(input string) (count int) {
@ -149,8 +150,7 @@ func word_count(input string) (count int) {
func getLevel(score int) (level int) {
var base float64 = 25
var current float64
var prev float64
var current, prev float64
exp_factor := 2.8
for i := 1;;i++ {
@ -170,8 +170,7 @@ func getLevel(score int) (level int) {
func getLevelScore(getLevel int) (score int) {
var base float64 = 25
var current float64
var prev float64
var current, prev float64
var level int
exp_factor := 2.8
@ -192,8 +191,7 @@ func getLevelScore(getLevel int) (score int) {
func getLevels(maxLevel int) []float64 {
var base float64 = 25
var current float64 = 0
var prev float64 = 0
var current, prev float64 // = 0
exp_factor := 2.8
var out []float64
out = append(out, 0)
@ -224,16 +222,16 @@ func fill_group_id_gap(biggerID int, smallerID int) {
}
}
func addModLog(action string, elementID int, elementType string, ipaddress string, actorID int) error {
_, err := add_modlog_entry_stmt.Exec(action,elementID,elementType,ipaddress,actorID)
func addModLog(action string, elementID int, elementType string, ipaddress string, actorID int) (err error) {
_, err = add_modlog_entry_stmt.Exec(action,elementID,elementType,ipaddress,actorID)
if err != nil {
return err
}
return nil
}
func addAdminLog(action string, elementID string, elementType int, ipaddress string, actorID int) error {
_, err := add_adminlog_entry_stmt.Exec(action,elementID,elementType,ipaddress,actorID)
func addAdminLog(action string, elementID string, elementType int, ipaddress string, actorID int) (err error) {
_, err = add_adminlog_entry_stmt.Exec(action,elementID,elementType,ipaddress,actorID)
if err != nil {
return err
}