aboutsummaryrefslogtreecommitdiff
path: root/forged/internal/common/misc
diff options
context:
space:
mode:
authorRunxi Yu <me@runxiyu.org>2025-08-12 11:01:07 +0800
committerRunxi Yu <me@runxiyu.org>2025-09-13 19:08:22 +0800
commit5717faed659a9eeb86c528ab56822c42eca1ad3f (patch)
tree92e6662628a51c03c52300d2fd98173716a82882 /forged/internal/common/misc
parentRemove forge-specific functions from misc (diff)
downloadforge-5717faed659a9eeb86c528ab56822c42eca1ad3f.tar.gz
forge-5717faed659a9eeb86c528ab56822c42eca1ad3f.tar.zst
forge-5717faed659a9eeb86c528ab56822c42eca1ad3f.zip
Refactor
Diffstat (limited to 'forged/internal/common/misc')
-rw-r--r--forged/internal/common/misc/back.go11
-rw-r--r--forged/internal/common/misc/iter.go23
-rw-r--r--forged/internal/common/misc/misc.go5
-rw-r--r--forged/internal/common/misc/net.go42
-rw-r--r--forged/internal/common/misc/slices.go17
-rw-r--r--forged/internal/common/misc/trivial.go48
-rw-r--r--forged/internal/common/misc/unsafe.go20
-rw-r--r--forged/internal/common/misc/url.go118
8 files changed, 284 insertions, 0 deletions
diff --git a/forged/internal/common/misc/back.go b/forged/internal/common/misc/back.go
new file mode 100644
index 0000000..5351359
--- /dev/null
+++ b/forged/internal/common/misc/back.go
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// SPDX-FileCopyrightText: Copyright (c) 2025 Runxi Yu <https://runxiyu.org>
+
+package misc
+
+// ErrorBack wraps a value and a channel for communicating an associated error.
+// Typically used to get an error response after sending data across a channel.
+type ErrorBack[T any] struct {
+ Content T
+ ErrorChan chan error
+}
diff --git a/forged/internal/common/misc/iter.go b/forged/internal/common/misc/iter.go
new file mode 100644
index 0000000..61a96f4
--- /dev/null
+++ b/forged/internal/common/misc/iter.go
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// SPDX-FileCopyrightText: Copyright (c) 2025 Runxi Yu <https://runxiyu.org>
+
+package misc
+
+import "iter"
+
+// iterSeqLimit returns an iterator equivalent to the supplied one, but stops
+// after n iterations.
+func IterSeqLimit[T any](s iter.Seq[T], n uint) iter.Seq[T] {
+ return func(yield func(T) bool) {
+ var iterations uint
+ for v := range s {
+ if iterations > n-1 {
+ return
+ }
+ if !yield(v) {
+ return
+ }
+ iterations++
+ }
+ }
+}
diff --git a/forged/internal/common/misc/misc.go b/forged/internal/common/misc/misc.go
new file mode 100644
index 0000000..e9e10ab
--- /dev/null
+++ b/forged/internal/common/misc/misc.go
@@ -0,0 +1,5 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// SPDX-FileCopyrightText: Copyright (c) 2025 Runxi Yu <https://runxiyu.org>
+
+// Package misc provides miscellaneous functions and other definitions.
+package misc
diff --git a/forged/internal/common/misc/net.go b/forged/internal/common/misc/net.go
new file mode 100644
index 0000000..967ea77
--- /dev/null
+++ b/forged/internal/common/misc/net.go
@@ -0,0 +1,42 @@
+package misc
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "net"
+ "syscall"
+)
+
+func ListenUnixSocket(ctx context.Context, path string) (listener net.Listener, replaced bool, err error) {
+ listenConfig := net.ListenConfig{} //exhaustruct:ignore
+ listener, err = listenConfig.Listen(ctx, "unix", path)
+ if errors.Is(err, syscall.EADDRINUSE) {
+ replaced = true
+ unlinkErr := syscall.Unlink(path)
+ if unlinkErr != nil {
+ return listener, false, fmt.Errorf("remove existing socket %q: %w", path, unlinkErr)
+ }
+ listener, err = listenConfig.Listen(ctx, "unix", path)
+ }
+ if err != nil {
+ return listener, replaced, fmt.Errorf("listen on unix socket %q: %w", path, err)
+ }
+ return listener, replaced, nil
+}
+
+func Listen(ctx context.Context, net_, addr string) (listener net.Listener, err error) {
+ if net_ == "unix" {
+ listener, _, err = ListenUnixSocket(ctx, addr)
+ if err != nil {
+ return listener, fmt.Errorf("listen unix socket for web: %w", err)
+ }
+ } else {
+ listenConfig := net.ListenConfig{} //exhaustruct:ignore
+ listener, err = listenConfig.Listen(ctx, net_, addr)
+ if err != nil {
+ return listener, fmt.Errorf("listen %s for web: %w", net_, err)
+ }
+ }
+ return listener, nil
+}
diff --git a/forged/internal/common/misc/slices.go b/forged/internal/common/misc/slices.go
new file mode 100644
index 0000000..3ad0211
--- /dev/null
+++ b/forged/internal/common/misc/slices.go
@@ -0,0 +1,17 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// SPDX-FileCopyrightText: Copyright (c) 2025 Runxi Yu <https://runxiyu.org>
+
+package misc
+
+import "strings"
+
+// sliceContainsNewlines returns true if and only if the given slice contains
+// one or more strings that contains newlines.
+func SliceContainsNewlines(s []string) bool {
+ for _, v := range s {
+ if strings.Contains(v, "\n") {
+ return true
+ }
+ }
+ return false
+}
diff --git a/forged/internal/common/misc/trivial.go b/forged/internal/common/misc/trivial.go
new file mode 100644
index 0000000..83901e0
--- /dev/null
+++ b/forged/internal/common/misc/trivial.go
@@ -0,0 +1,48 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// SPDX-FileCopyrightText: Copyright (c) 2025 Runxi Yu <https://runxiyu.org>
+
+package misc
+
+import (
+ "net/url"
+ "strings"
+)
+
+// These are all trivial functions that are intended to be used in HTML
+// templates.
+
+// FirstLine returns the first line of a string.
+func FirstLine(s string) string {
+ before, _, _ := strings.Cut(s, "\n")
+ return before
+}
+
+// PathEscape escapes the input as an URL path segment.
+func PathEscape(s string) string {
+ return url.PathEscape(s)
+}
+
+// QueryEscape escapes the input as an URL query segment.
+func QueryEscape(s string) string {
+ return url.QueryEscape(s)
+}
+
+// Dereference dereferences a pointer.
+func Dereference[T any](p *T) T { //nolint:ireturn
+ return *p
+}
+
+// DereferenceOrZero dereferences a pointer. If the pointer is nil, the zero
+// value of its associated type is returned instead.
+func DereferenceOrZero[T any](p *T) T { //nolint:ireturn
+ if p != nil {
+ return *p
+ }
+ var z T
+ return z
+}
+
+// Minus subtracts two numbers.
+func Minus(a, b int) int {
+ return a - b
+}
diff --git a/forged/internal/common/misc/unsafe.go b/forged/internal/common/misc/unsafe.go
new file mode 100644
index 0000000..d827e7f
--- /dev/null
+++ b/forged/internal/common/misc/unsafe.go
@@ -0,0 +1,20 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// SPDX-FileCopyrightText: Copyright (c) 2025 Runxi Yu <https://runxiyu.org>
+
+package misc
+
+import "unsafe"
+
+// StringToBytes converts a string to a byte slice without copying the string.
+// Memory is borrowed from the string.
+// The resulting byte slice must not be modified in any form.
+func StringToBytes(s string) (bytes []byte) {
+ return unsafe.Slice(unsafe.StringData(s), len(s)) //#nosec G103
+}
+
+// BytesToString converts a byte slice to a string without copying the bytes.
+// Memory is borrowed from the byte slice.
+// The source byte slice must not be modified.
+func BytesToString(b []byte) string {
+ return unsafe.String(unsafe.SliceData(b), len(b)) //#nosec G103
+}
diff --git a/forged/internal/common/misc/url.go b/forged/internal/common/misc/url.go
new file mode 100644
index 0000000..346ff76
--- /dev/null
+++ b/forged/internal/common/misc/url.go
@@ -0,0 +1,118 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// SPDX-FileCopyrightText: Copyright (c) 2025 Runxi Yu <https://runxiyu.org>
+
+package misc
+
+import (
+ "net/http"
+ "net/url"
+ "strings"
+)
+
+// ParseReqURI parses an HTTP request URL, and returns a slice of path segments
+// and the query parameters. It handles %2F correctly.
+func ParseReqURI(requestURI string) (segments []string, params url.Values, err error) {
+ path, paramsStr, _ := strings.Cut(requestURI, "?")
+
+ segments, err = PathToSegments(path)
+ if err != nil {
+ return
+ }
+
+ params, err = url.ParseQuery(paramsStr)
+ return
+}
+
+// PathToSegments splits a path into unescaped segments. It handles %2F correctly.
+func PathToSegments(path string) (segments []string, err error) {
+ segments = strings.Split(strings.TrimPrefix(path, "/"), "/")
+
+ for i, segment := range segments {
+ segments[i], err = url.PathUnescape(segment)
+ if err != nil {
+ return
+ }
+ }
+
+ return
+}
+
+// RedirectDir returns true and redirects the user to a version of the URL with
+// a trailing slash, if and only if the request URL does not already have a
+// trailing slash.
+func RedirectDir(writer http.ResponseWriter, request *http.Request) bool {
+ requestURI := request.RequestURI
+
+ pathEnd := strings.IndexAny(requestURI, "?#")
+ var path, rest string
+ if pathEnd == -1 {
+ path = requestURI
+ } else {
+ path = requestURI[:pathEnd]
+ rest = requestURI[pathEnd:]
+ }
+
+ if !strings.HasSuffix(path, "/") {
+ http.Redirect(writer, request, path+"/"+rest, http.StatusSeeOther)
+ return true
+ }
+ return false
+}
+
+// RedirectNoDir returns true and redirects the user to a version of the URL
+// without a trailing slash, if and only if the request URL has a trailing
+// slash.
+func RedirectNoDir(writer http.ResponseWriter, request *http.Request) bool {
+ requestURI := request.RequestURI
+
+ pathEnd := strings.IndexAny(requestURI, "?#")
+ var path, rest string
+ if pathEnd == -1 {
+ path = requestURI
+ } else {
+ path = requestURI[:pathEnd]
+ rest = requestURI[pathEnd:]
+ }
+
+ if strings.HasSuffix(path, "/") {
+ http.Redirect(writer, request, strings.TrimSuffix(path, "/")+rest, http.StatusSeeOther)
+ return true
+ }
+ return false
+}
+
+// RedirectUnconditionally unconditionally redirects the user back to the
+// current page while preserving query parameters.
+func RedirectUnconditionally(writer http.ResponseWriter, request *http.Request) {
+ requestURI := request.RequestURI
+
+ pathEnd := strings.IndexAny(requestURI, "?#")
+ var path, rest string
+ if pathEnd == -1 {
+ path = requestURI
+ } else {
+ path = requestURI[:pathEnd]
+ rest = requestURI[pathEnd:]
+ }
+
+ http.Redirect(writer, request, path+rest, http.StatusSeeOther)
+}
+
+// SegmentsToURL joins URL segments to the path component of a URL.
+// Each segment is escaped properly first.
+func SegmentsToURL(segments []string) string {
+ for i, segment := range segments {
+ segments[i] = url.PathEscape(segment)
+ }
+ return strings.Join(segments, "/")
+}
+
+// AnyContain returns true if and only if ss contains a string that contains c.
+func AnyContain(ss []string, c string) bool {
+ for _, s := range ss {
+ if strings.Contains(s, c) {
+ return true
+ }
+ }
+ return false
+}