Lindenii Project Forge
Login
Commit info
ID91ca7bf1baf7ab077bdd63a7a3930c15af5be325
AuthorRunxi Yu<me@runxiyu.org>
Author dateThu, 13 Feb 2025 09:33:19 +0800
CommitterRunxi Yu<me@runxiyu.org>
Committer dateThu, 13 Feb 2025 09:33:19 +0800
Actions
Get patch
http_*.go: Use http.Error
package main

import (
	"bufio"
	"context"
	"errors"
	"os"

	"github.com/jackc/pgx/v5/pgxpool"
	"go.lindenii.runxiyu.org/lindenii-common/scfg"
)

var database *pgxpool.Pool

var err_unsupported_database_type = errors.New("Unsupported database type")

var config struct {
	HTTP struct {
		Net  string `scfg:"net"`
		Addr string `scfg:"addr"`
		CookieExpiry int `scfg:"cookie_expiry"`
		Net          string `scfg:"net"`
		Addr         string `scfg:"addr"`
		CookieExpiry int    `scfg:"cookie_expiry"`
	} `scfg:"http"`
	SSH struct {
		Net  string `scfg:"net"`
		Addr string `scfg:"addr"`
		Key  string `scfg:"key"`
	} `scfg:"ssh"`
	Git struct {
		Root string `scfg:"root"`
	} `scfg:"git"`
	DB struct {
		Type string `scfg:"type"`
		Conn string `scfg:"conn"`
	} `scfg:"db"`
}

func load_config(path string) (err error) {
	config_file, err := os.Open(path)
	if err != nil {
		return err
	}
	defer config_file.Close()

	decoder := scfg.NewDecoder(bufio.NewReader(config_file))
	err = decoder.Decode(&config)
	if err != nil {
		return err
	}

	if config.DB.Type != "postgres" {
		return err_unsupported_database_type
	}
	database, err = pgxpool.New(context.Background(), config.DB.Conn)
	if err != nil {
		return err
	}

	return nil
}
package main

import (
	"fmt"
	"net/http"
)

func handle_group_repos(w http.ResponseWriter, r *http.Request, params map[string]any) {
	group_name := params["group_name"]

	var names []string
	rows, err := database.Query(r.Context(), "SELECT r.name FROM repos r JOIN groups g ON r.group_id = g.id WHERE g.name = $1;", group_name)
	if err != nil {
		fmt.Fprintln(w, "Error getting groups:", err.Error())
		http.Error(w, "Error getting groups:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	for rows.Next() {
		var name string
		if err := rows.Scan(&name); err != nil {
			fmt.Fprintln(w, "Error scanning row:", err.Error())
			http.Error(w, "Error scanning row:: "+err.Error(), http.StatusInternalServerError)
			return
		}
		names = append(names, name)
	}

	if err := rows.Err(); err != nil {
		fmt.Fprintln(w, "Error iterating over rows:", err.Error())
		http.Error(w, "Error iterating over rows:: "+err.Error(), http.StatusInternalServerError)
		return
	}

	params["repos"] = names

	err = templates.ExecuteTemplate(w, "group_repos", params)
	if err != nil {
		fmt.Fprintln(w, "Error rendering template:", err.Error())
		http.Error(w, "Error rendering template:: "+err.Error(), http.StatusInternalServerError)
		return
	}
}
package main

import (
	"fmt"
	"net/http"
)

func handle_index(w http.ResponseWriter, r *http.Request, params map[string]any) {
	rows, err := database.Query(r.Context(), "SELECT name FROM groups")
	if err != nil {
		fmt.Fprintln(w, "Error querying groups: " + err.Error())
		http.Error(w, "Error querying groups: : "+err.Error(), http.StatusInternalServerError)
		return
	}
	defer rows.Close()

	groups := []string{}
	for rows.Next() {
		var groupName string
		if err := rows.Scan(&groupName); err != nil {
			fmt.Fprintln(w, "Error scanning group name: " + err.Error())
			http.Error(w, "Error scanning group name: : "+err.Error(), http.StatusInternalServerError)
			return
		}
		groups = append(groups, groupName)
	}

	if err := rows.Err(); err != nil {
		fmt.Fprintln(w, "Error iterating over rows: " + err.Error())
		http.Error(w, "Error iterating over rows: : "+err.Error(), http.StatusInternalServerError)
		return
	}

	params["groups"] = groups

	err = templates.ExecuteTemplate(w, "index", params)
	if err != nil {
		fmt.Fprintln(w, "Error rendering template: " + err.Error())
		http.Error(w, "Error rendering template: : "+err.Error(), http.StatusInternalServerError)
		return
	}
}
package main

import (
	"crypto/rand"
	"encoding/base64"
	"errors"
	"fmt"
	"net/http"
	"time"

	"github.com/alexedwards/argon2id"
	"github.com/jackc/pgx/v5"
)

func handle_login(w http.ResponseWriter, r *http.Request, params map[string]any) {
	if r.Method != "POST" {
		err := templates.ExecuteTemplate(w, "login", params)
		if err != nil {
			fmt.Fprintln(w, "Error rendering template:", err.Error())
			http.Error(w, "Error rendering template:: "+err.Error(), http.StatusInternalServerError)
		}
		return
	}

	var user_id int
	username := r.PostFormValue("username")
	password := r.PostFormValue("password")

	var password_hash string
	err := database.QueryRow(r.Context(), "SELECT id, password FROM users WHERE username = $1", username).Scan(&user_id, &password_hash)
	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			params["login_error"] = "Unknown username"
			err := templates.ExecuteTemplate(w, "login", params)
			if err != nil {
				fmt.Fprintln(w, "Error rendering template:", err.Error())
				http.Error(w, "Error rendering template:: "+err.Error(), http.StatusInternalServerError)
			}
			return
		}
		fmt.Fprintln(w, "Error querying user information:", err.Error())
		http.Error(w, "Error querying user information:: "+err.Error(), http.StatusInternalServerError)
		return
	}

	match, err := argon2id.ComparePasswordAndHash(password, password_hash)
	if err != nil {
		fmt.Fprintln(w, "Error comparing password and hash:", err.Error())
		http.Error(w, "Error comparing password and hash:: "+err.Error(), http.StatusInternalServerError)
		return
	}

	if !match {
		params["login_error"] = "Invalid password"
		err := templates.ExecuteTemplate(w, "login", params)
		if err != nil {
			fmt.Fprintln(w, "Error rendering template:", err.Error())
			http.Error(w, "Error rendering template:: "+err.Error(), http.StatusInternalServerError)
			return
		}
		return
	}

	cookie_value, err := random_urlsafe_string(16)
	now := time.Now()
	expiry := now.Add(time.Duration(config.HTTP.CookieExpiry) * time.Second)

	cookie := http.Cookie{
		Name:     "session",
		Value:    cookie_value,
		SameSite: http.SameSiteLaxMode,
		HttpOnly: true,
		Secure:   false, // TODO
		Expires:  expiry,
		Path:     "/",
		// TODO: Expire
	}

	http.SetCookie(w, &cookie)

	_, err = database.Exec(r.Context(), "INSERT INTO sessions (user_id, session_id) VALUES ($1, $2)", user_id, cookie_value)
	if err != nil {
		fmt.Fprintln(w, "Error inserting session:", err.Error())
		http.Error(w, "Error inserting session:: "+err.Error(), http.StatusInternalServerError)
		return
	}

	http.Redirect(w, r, "/", http.StatusSeeOther)
}

func random_urlsafe_string(sz int) (string, error) {
	r := make([]byte, 3*sz)
	_, err := rand.Read(r)
	if err != nil {
		return "", fmt.Errorf("error generating random string: %w", err)
	}
	return base64.RawURLEncoding.EncodeToString(r), nil
}
package main

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/go-git/go-git/v5/plumbing"
	"github.com/go-git/go-git/v5/plumbing/filemode"
	"github.com/go-git/go-git/v5/plumbing/format/diff"
	"go.lindenii.runxiyu.org/lindenii-common/misc"
)

type usable_file_patch struct {
	From   diff.File
	To     diff.File
	Chunks []diff.Chunk
}

func handle_repo_commit(w http.ResponseWriter, r *http.Request, params map[string]any) {
	group_name, repo_name, commit_id_specified_string := params["group_name"].(string), params["repo_name"].(string), params["commit_id"].(string)
	repo, description, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		fmt.Fprintln(w, "Error opening repo:", err.Error())
		http.Error(w, "Error opening repo:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["repo_description"] = description
	commit_id_specified_string_without_suffix := strings.TrimSuffix(commit_id_specified_string, ".patch")
	commit_id := plumbing.NewHash(commit_id_specified_string_without_suffix)
	commit_object, err := repo.CommitObject(commit_id)
	if err != nil {
		fmt.Fprintln(w, "Error getting commit object:", err.Error())
		http.Error(w, "Error getting commit object:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	if commit_id_specified_string_without_suffix != commit_id_specified_string {
		patch, err := format_patch_from_commit(commit_object)
		if err != nil {
			fmt.Fprintln(w, "Error formatting patch:", err.Error())
			http.Error(w, "Error formatting patch:: "+err.Error(), http.StatusInternalServerError)
			return
		}
		fmt.Fprintln(w, patch)
		return
	}
	commit_id_string := commit_object.Hash.String()

	if commit_id_string != commit_id_specified_string {
		http.Redirect(w, r, commit_id_string, http.StatusSeeOther)
		return
	}

	params["commit_object"] = commit_object
	params["commit_id"] = commit_id_string

	parent_commit_hash, patch, err := get_patch_from_commit(commit_object)
	if err != nil {
		fmt.Fprintln(w, "Error getting patch from commit:", err.Error())
		http.Error(w, "Error getting patch from commit:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["parent_commit_hash"] = parent_commit_hash.String()
	params["patch"] = patch

	// TODO: Remove unnecessary context                                          
	// TODO: Remove unnecessary context
	// TODO: Prepend "+"/"-"/" " instead of solely distinguishing based on color
	usable_file_patches := make([]usable_file_patch, 0)
	for _, file_patch := range patch.FilePatches() {
		from, to := file_patch.Files()
		if from == nil {
			from = fake_diff_file_null
		}
		if to == nil {
			to = fake_diff_file_null
		}
		usable_file_patch := usable_file_patch{
			Chunks: file_patch.Chunks(),
			From:   from,
			To:     to,
		}
		usable_file_patches = append(usable_file_patches, usable_file_patch)
	}
	params["file_patches"] = usable_file_patches

	err = templates.ExecuteTemplate(w, "repo_commit", params)
	if err != nil {
		fmt.Fprintln(w, "Error rendering template:", err.Error())
		http.Error(w, "Error rendering template:: "+err.Error(), http.StatusInternalServerError)
		return
	}
}

type fake_diff_file struct {
	hash plumbing.Hash
	mode filemode.FileMode
	path string
}

func (f fake_diff_file) Hash() plumbing.Hash {
	return f.hash
}

func (f fake_diff_file) Mode() filemode.FileMode {
	return f.mode
}

func (f fake_diff_file) Path() string {
	return f.path
}

var fake_diff_file_null = fake_diff_file{
	hash: plumbing.NewHash("e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"),
	mode: misc.First_or_panic(filemode.New("100644")),
	path: "",
}
package main

import (
	"fmt"
	"net/http"
	"net/url"
)

func handle_repo_index(w http.ResponseWriter, r *http.Request, params map[string]any) {
	group_name, repo_name := params["group_name"].(string), params["repo_name"].(string)
	repo, description, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		fmt.Fprintln(w, "Error opening repo:", err.Error())
		http.Error(w, "Error opening repo:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["repo_description"] = description
	head, err := repo.Head()
	if err != nil {
		fmt.Fprintln(w, "Error getting repo HEAD:", err.Error())
		http.Error(w, "Error getting repo HEAD:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["ref"] = head.Name().Short()
	head_hash := head.Hash()
	recent_commits, err := get_recent_commits(repo, head_hash, 3)
	if err != nil {
		fmt.Fprintln(w, "Error getting recent commits:", err.Error())
		http.Error(w, "Error getting recent commits:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["commits"] = recent_commits
	commit_object, err := repo.CommitObject(head_hash)
	if err != nil {
		fmt.Fprintln(w, "Error getting commit object:", err.Error())
		http.Error(w, "Error getting commit object:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	tree, err := commit_object.Tree()
	if err != nil {
		fmt.Fprintln(w, "Error getting file tree:", err.Error())
		http.Error(w, "Error getting file tree:: "+err.Error(), http.StatusInternalServerError)
		return
	}

	params["readme_filename"], params["readme"] = render_readme_at_tree(tree)
	params["files"] = build_display_git_tree(tree)

	params["clone_url"] = "ssh://" + r.Host + "/" + url.PathEscape(group_name) + "/:/repos/" + url.PathEscape(repo_name)

	err = templates.ExecuteTemplate(w, "repo_index", params)
	if err != nil {
		fmt.Fprintln(w, "Error rendering template:", err.Error())
		http.Error(w, "Error rendering template:: "+err.Error(), http.StatusInternalServerError)
		return
	}
}
package main

import (
	"fmt"
	"net/http"

	"github.com/go-git/go-git/v5/plumbing"
)

// TODO: I probably shouldn't include *all* commits here...
func handle_repo_log(w http.ResponseWriter, r *http.Request, params map[string]any) {
	group_name, repo_name, ref_name := params["group_name"].(string), params["repo_name"].(string), params["ref"].(string)
	repo, description, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		fmt.Fprintln(w, "Error opening repo:", err.Error())
		http.Error(w, "Error opening repo:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["repo_description"] = description
	ref, err := repo.Reference(plumbing.NewBranchReferenceName(ref_name), true)
	if err != nil {
		fmt.Fprintln(w, "Error getting repo reference:", err.Error())
		http.Error(w, "Error getting repo reference:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	ref_hash := ref.Hash()
	commits, err := get_recent_commits(repo, ref_hash, -1)
	if err != nil {
		fmt.Fprintln(w, "Error getting recent commits:", err.Error())
		http.Error(w, "Error getting recent commits:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["commits"] = commits

	err = templates.ExecuteTemplate(w, "repo_log", params)
	if err != nil {
		fmt.Fprintln(w, "Error rendering template:", err.Error())
		http.Error(w, "Error rendering template:: "+err.Error(), http.StatusInternalServerError)
		return
	}
}
package main

import (
	"fmt"
	"errors"
	"fmt"
	"net/http"
	"path"
	"strings"

	"github.com/go-git/go-git/v5/plumbing/object"
)

func handle_repo_raw(w http.ResponseWriter, r *http.Request, params map[string]any) {
	raw_path_spec := params["rest"].(string)
	group_name, repo_name, path_spec := params["group_name"].(string), params["repo_name"].(string), strings.TrimSuffix(raw_path_spec, "/")

	ref_type, ref_name, err := get_param_ref_and_type(r)
	if err != nil {
		if errors.Is(err, err_no_ref_spec) {
			ref_type = "head"
		} else {
			fmt.Fprintln(w, "Error querying ref type:", err.Error())
			http.Error(w, "Error querying ref type:: "+err.Error(), http.StatusInternalServerError)
			return
		}
	}

	params["ref_type"], params["ref"], params["path_spec"] = ref_type, ref_name, path_spec

	repo, description, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		fmt.Fprintln(w, "Error opening repo:", err.Error())
		http.Error(w, "Error opening repo:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["repo_description"] = description

	ref_hash, err := get_ref_hash_from_type_and_name(repo, ref_type, ref_name)
	if err != nil {
		fmt.Fprintln(w, "Error getting ref hash:", err.Error())
		http.Error(w, "Error getting ref hash:: "+err.Error(), http.StatusInternalServerError)
		return
	}

	commit_object, err := repo.CommitObject(ref_hash)
	if err != nil {
		fmt.Fprintln(w, "Error getting commit object:", err.Error())
		http.Error(w, "Error getting commit object:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	tree, err := commit_object.Tree()
	if err != nil {
		fmt.Fprintln(w, "Error getting file tree:", err.Error())
		http.Error(w, "Error getting file tree:: "+err.Error(), http.StatusInternalServerError)
		return
	}

	var target *object.Tree
	if path_spec == "" {
		target = tree
	} else {
		target, err = tree.Tree(path_spec)
		if err != nil {
			file, err := tree.File(path_spec)
			if err != nil {
				fmt.Fprintln(w, "Error retrieving path:", err.Error())
				http.Error(w, "Error retrieving path:: "+err.Error(), http.StatusInternalServerError)
				return
			}
			if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] == '/' {
				http.Redirect(w, r, "../"+path_spec, http.StatusSeeOther)
				return
			}
			file_contents, err := file.Contents()
			if err != nil {
				fmt.Fprintln(w, "Error reading file:", err.Error())
				http.Error(w, "Error reading file:: "+err.Error(), http.StatusInternalServerError)
				return
			}
			fmt.Fprintln(w, file_contents)
			return
		}
	}

	if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] != '/' {
		http.Redirect(w, r, path.Base(path_spec)+"/", http.StatusSeeOther)
		return
	}

	params["files"] = build_display_git_tree(target)

	err = templates.ExecuteTemplate(w, "repo_raw_dir", params)
	if err != nil {
		fmt.Fprintln(w, "Error rendering template:", err.Error())
		http.Error(w, "Error rendering template:: "+err.Error(), http.StatusInternalServerError)
		return
	}
}
package main

import (
	"bytes"
	"errors"
	"fmt"
	"html/template"
	"net/http"
	"path"
	"strings"

	chroma_formatters_html "github.com/alecthomas/chroma/v2/formatters/html"
	chroma_lexers "github.com/alecthomas/chroma/v2/lexers"
	chroma_styles "github.com/alecthomas/chroma/v2/styles"
	"github.com/go-git/go-git/v5/plumbing/object"
)

func handle_repo_tree(w http.ResponseWriter, r *http.Request, params map[string]any) {
	raw_path_spec := params["rest"].(string)
	group_name, repo_name, path_spec := params["group_name"].(string), params["repo_name"].(string), strings.TrimSuffix(raw_path_spec, "/")
	ref_type, ref_name, err := get_param_ref_and_type(r)
	if err != nil {
		if errors.Is(err, err_no_ref_spec) {
			ref_type = "head"
		} else {
			fmt.Fprintln(w, "Error querying ref type:", err.Error())
			http.Error(w, "Error querying ref type:: "+err.Error(), http.StatusInternalServerError)
			return
		}
	}
	params["ref_type"], params["ref"], params["path_spec"] = ref_type, ref_name, path_spec
	repo, description, err := open_git_repo(r.Context(), group_name, repo_name)
	if err != nil {
		fmt.Fprintln(w, "Error opening repo:", err.Error())
		http.Error(w, "Error opening repo:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	params["repo_description"] = description

	ref_hash, err := get_ref_hash_from_type_and_name(repo, ref_type, ref_name)
	if err != nil {
		fmt.Fprintln(w, "Error getting ref hash:", err.Error())
		http.Error(w, "Error getting ref hash:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	commit_object, err := repo.CommitObject(ref_hash)
	if err != nil {
		fmt.Fprintln(w, "Error getting commit object:", err.Error())
		http.Error(w, "Error getting commit object:: "+err.Error(), http.StatusInternalServerError)
		return
	}
	tree, err := commit_object.Tree()
	if err != nil {
		fmt.Fprintln(w, "Error getting file tree:", err.Error())
		http.Error(w, "Error getting file tree:: "+err.Error(), http.StatusInternalServerError)
		return
	}

	var target *object.Tree
	if path_spec == "" {
		target = tree
	} else {
		target, err = tree.Tree(path_spec)
		if err != nil {
			file, err := tree.File(path_spec)
			if err != nil {
				fmt.Fprintln(w, "Error retrieving path:", err.Error())
				http.Error(w, "Error retrieving path:: "+err.Error(), http.StatusInternalServerError)
				return
			}
			if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] == '/' {
				http.Redirect(w, r, "../"+path_spec, http.StatusSeeOther)
				return
			}
			file_contents, err := file.Contents()
			if err != nil {
				fmt.Fprintln(w, "Error reading file:", err.Error())
				http.Error(w, "Error reading file:: "+err.Error(), http.StatusInternalServerError)
				return
			}
			lexer := chroma_lexers.Match(path_spec)
			if lexer == nil {
				lexer = chroma_lexers.Fallback
			}
			iterator, err := lexer.Tokenise(nil, file_contents)
			if err != nil {
				fmt.Fprintln(w, "Error tokenizing code:", err.Error())
				http.Error(w, "Error tokenizing code:: "+err.Error(), http.StatusInternalServerError)
				return
			}
			var formatted_unencapsulated bytes.Buffer
			style := chroma_styles.Get("autumn")
			formatter := chroma_formatters_html.New(chroma_formatters_html.WithClasses(true), chroma_formatters_html.TabWidth(8))
			err = formatter.Format(&formatted_unencapsulated, style, iterator)
			if err != nil {
				fmt.Fprintln(w, "Error formatting code:", err.Error())
				http.Error(w, "Error formatting code:: "+err.Error(), http.StatusInternalServerError)
				return
			}
			formatted_encapsulated := template.HTML(formatted_unencapsulated.Bytes())
			params["file_contents"] = formatted_encapsulated

			err = templates.ExecuteTemplate(w, "repo_tree_file", params)
			if err != nil {
				fmt.Fprintln(w, "Error rendering template:", err.Error())
				http.Error(w, "Error rendering template:: "+err.Error(), http.StatusInternalServerError)
				return
			}
			return
		}
	}

	if len(raw_path_spec) != 0 && raw_path_spec[len(raw_path_spec)-1] != '/' {
		http.Redirect(w, r, path.Base(path_spec)+"/", http.StatusSeeOther)
		return
	}

	params["readme_filename"], params["readme"] = render_readme_at_tree(target)
	params["files"] = build_display_git_tree(target)

	err = templates.ExecuteTemplate(w, "repo_tree_dir", params)
	if err != nil {
		fmt.Fprintln(w, "Error rendering template:", err.Error())
		http.Error(w, "Error rendering template:: "+err.Error(), http.StatusInternalServerError)
		return
	}
}
package main

import (
	"fmt"
	"net/http"
)

func handle_users(w http.ResponseWriter, r *http.Request, params map[string]any) {
	fmt.Fprintln(w, "Not implemented")
	http.Error(w, "Not implemented", http.StatusNotImplemented)
}
package main

import (
	"errors"
	"fmt"
	"net/http"
	"strings"
	"strconv"
	"strings"
)

type http_router_t struct{}

func (router *http_router_t) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	segments, _, err := parse_request_uri(r.RequestURI)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	non_empty_last_segments_len := len(segments)
	dir_mode := false
	if segments[len(segments)-1] == "" {
		non_empty_last_segments_len--
		dir_mode = true
	}

	if segments[0] == ":" {
		if len(segments) < 2 {
			http.Error(w, "Blank system endpoint", http.StatusNotFound)
			return
		} else if len(segments) == 2 && !dir_mode {
			http.Redirect(w, r, r.URL.Path+"/", http.StatusSeeOther)
			return
		}

		switch segments[1] {
		case "static":
			static_handler.ServeHTTP(w, r)
			return
		case "source":
			source_handler.ServeHTTP(w, r)
			return
		}
	}

	params := make(map[string]any)
	params["global"] = global_data
	var _user_id int
	_user_id, params["username"], err = get_user_info_from_request(r)
	if _user_id == 0 {
		params["user_id"] = ""
	} else {
		params["user_id"] = strconv.Itoa(_user_id)
	}

	if segments[0] == ":" {
		switch segments[1] {
		case "login":
			handle_login(w, r, params)
			return
		case "users":
			handle_users(w, r, params)
			return
		default:
			http.Error(w, fmt.Sprintf("Unknown system module type: %s", segments[1]), http.StatusNotFound)
			return
		}
	}

	separator_index := -1
	for i, part := range segments {
		if part == ":" {
			separator_index = i
			break
		}
	}

	switch {
	case non_empty_last_segments_len == 0:
		handle_index(w, r, params)
	case separator_index == -1:
		http.Error(w, "Group indexing hasn't been implemented yet", http.StatusNotImplemented)
	case non_empty_last_segments_len == separator_index+1:
		http.Error(w, "Group root hasn't been implemented yet", http.StatusNotImplemented)
	case non_empty_last_segments_len == separator_index+2:
		if !dir_mode {
			http.Redirect(w, r, r.URL.Path+"/", http.StatusSeeOther)
			return
		}
		module_type := segments[separator_index+1]
		params["group_name"] = segments[0]
		switch module_type {
		case "repos":
			handle_group_repos(w, r, params)
		default:
			http.Error(w, fmt.Sprintf("Unknown module type: %s", module_type), http.StatusNotFound)
		}
	default:
		module_type := segments[separator_index+1]
		module_name := segments[separator_index+2]
		params["group_name"] = segments[0]
		switch module_type {
		case "repos":
			params["repo_name"] = module_name
			// TODO: subgroups
			if non_empty_last_segments_len == separator_index+3 {
				if !dir_mode {
					http.Redirect(w, r, r.URL.Path+"/", http.StatusSeeOther)
					return
				}
				handle_repo_index(w, r, params)
				return
			}
			repo_feature := segments[separator_index+3]
			switch repo_feature {
			case "info":
				handle_repo_info(w, r, params)
			case "tree":
				params["rest"] = strings.Join(segments[separator_index+4:], "/")
				handle_repo_tree(w, r, params)
			case "raw":
				params["rest"] = strings.Join(segments[separator_index+4:], "/")
				handle_repo_raw(w, r, params)
			case "log":
				if non_empty_last_segments_len != separator_index+5 {
					http.Error(w, "Too many parameters", http.StatusBadRequest)
					return
				}
				if dir_mode {
					http.Redirect(w, r, strings.TrimSuffix(r.URL.Path, "/"), http.StatusSeeOther)
					return
				}
				params["ref"] = segments[separator_index+4]
				handle_repo_log(w, r, params)
			case "commit":
				if dir_mode {
					http.Redirect(w, r, strings.TrimSuffix(r.URL.Path, "/"), http.StatusSeeOther)
					return
				}
				params["commit_id"] = segments[separator_index+4]
				handle_repo_commit(w, r, params)
			default:
				http.Error(w, fmt.Sprintf("Unknown repo feature: %s", repo_feature), http.StatusNotFound)
			}
		default:
			http.Error(w, fmt.Sprintf("Unknown module type: %s", module_type), http.StatusNotFound)
		}
	}
}

var err_bad_request = errors.New("Bad Request")