aboutsummaryrefslogtreecommitdiffhomepage
path: root/server.go
diff options
context:
space:
mode:
authornsfisis <nsfisis@gmail.com>2026-02-05 00:03:11 +0900
committernsfisis <nsfisis@gmail.com>2026-02-05 00:03:45 +0900
commit3f87e9a4d522d9b2d003b9eb2bb610dc164dae08 (patch)
tree8daa034bf2ca65982738f84ff3ece9baefa969ba /server.go
parent05a77ee41ebe35a38763ff9722357fa76d988a36 (diff)
downloadnilink-3f87e9a4d522d9b2d003b9eb2bb610dc164dae08.tar.gz
nilink-3f87e9a4d522d9b2d003b9eb2bb610dc164dae08.tar.zst
nilink-3f87e9a4d522d9b2d003b9eb2bb610dc164dae08.zip
add files
Diffstat (limited to 'server.go')
-rw-r--r--server.go61
1 files changed, 61 insertions, 0 deletions
diff --git a/server.go b/server.go
new file mode 100644
index 0000000..df98893
--- /dev/null
+++ b/server.go
@@ -0,0 +1,61 @@
+package main
+
+import (
+ "database/sql"
+ "flag"
+ "fmt"
+ "net/http"
+ "os"
+ "strings"
+)
+
+func newMux(db *sql.DB) http.Handler {
+ mux := http.NewServeMux()
+ mux.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "text/plain")
+ fmt.Fprint(w, "User-agent: *\nDisallow: /\n")
+ })
+ mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
+ path := strings.TrimPrefix(r.URL.Path, "/")
+ if path == "" {
+ http.Error(w, "not found", http.StatusNotFound)
+ return
+ }
+ if strings.Contains(path, "/") {
+ http.Error(w, "not found", http.StatusNotFound)
+ return
+ }
+ id, err := decodeID(path)
+ if err != nil {
+ http.Error(w, "not found", http.StatusNotFound)
+ return
+ }
+ url, err := getURL(db, id)
+ if err != nil {
+ http.Error(w, "not found", http.StatusNotFound)
+ return
+ }
+ http.Redirect(w, r, url, http.StatusMovedPermanently)
+ })
+ return mux
+}
+
+func cmdServe(args []string) {
+ fs := flag.NewFlagSet("serve", flag.ExitOnError)
+ addr := fs.String("addr", ":8080", "listen address")
+ dbPath := fs.String("db", "nilink.db", "database path")
+ fs.Parse(args)
+
+ db, err := openDB(*dbPath)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, "error: %v\n", err)
+ os.Exit(1)
+ }
+ defer db.Close()
+
+ fmt.Fprintf(os.Stderr, "listening on %s\n", *addr)
+ if err := http.ListenAndServe(*addr, newMux(db)); err != nil {
+ fmt.Fprintf(os.Stderr, "error: %v\n", err)
+ os.Exit(1)
+ }
+}