| author | Alberto Bertogli
<albertito@blitiri.com.ar> 2026-10-30 19:49:15 UTC |
| committer | Alberto Bertogli
<albertito@blitiri.com.ar> 2026-11-06 23:57:34 UTC |
| parent | b946735db47478e619e18ed11004053f592f563f |
| debug/debug.go | +2 | -2 |
| gofer.go | +2 | -2 |
| gofer_test.go | +2 | -2 |
| ipratelimit/ipratelimit.go | +1 | -4 |
| ipratelimit/ipratelimit_test.go | +8 | -8 |
| nettrace/bench_test.go | +3 | -5 |
| nettrace/http.go | +3 | -3 |
| nettrace/trace.go | +4 | -6 |
| ratelimit/ratelimit.go | +3 | -7 |
| server/auth.go | +0 | -1 |
| server/fileserver.go | +7 | -11 |
| server/http.go | +4 | -4 |
| server/peruser_test.go | +3 | -2 |
| server/server_test.go | +2 | -3 |
| test/util/exp/exp.go | +11 | -19 |
| util/util.go | +3 | -2 |
diff --git a/debug/debug.go b/debug/debug.go index 24995d2..eb24f9c 100644 --- a/debug/debug.go +++ b/debug/debug.go @@ -91,10 +91,10 @@ func ServeDebugging(addr string, conf *config.Config) error { } func DumpConfigFunc(conf *config.Config) http.HandlerFunc { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.Write([]byte(conf.String())) - }) + } } // Functions available inside the templates. diff --git a/gofer.go b/gofer.go index a390e8a..425f042 100644 --- a/gofer.go +++ b/gofer.go @@ -57,7 +57,7 @@ func main() { for name, rlog := range conf.ReqLog { err := reqlog.FromConfig(name, rlog) if err != nil { - log.Fatalf(err.Error()) + log.Fatalf("%v", err) } } @@ -92,7 +92,7 @@ func main() { } err = runMany(servers...) - log.Fatalf(err.Error()) + log.Fatalf("%v", err) } func signalHandler() { diff --git a/gofer_test.go b/gofer_test.go index 7d1bdda..f366c11 100644 --- a/gofer_test.go +++ b/gofer_test.go @@ -1,7 +1,7 @@ package main import ( - "io/ioutil" + "io" "net/http" "net/http/httptest" "strings" @@ -23,7 +23,7 @@ func TestDumpConfig(t *testing.T) { if err != nil { t.Fatal(err) } - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) res.Body.Close() if err != nil { t.Fatal(err) diff --git a/ipratelimit/ipratelimit.go b/ipratelimit/ipratelimit.go index 7fc3808..a7642e6 100644 --- a/ipratelimit/ipratelimit.go +++ b/ipratelimit/ipratelimit.go @@ -103,10 +103,7 @@ type entry struct { } func (e *entry) reset() { - e.lastAllowed = 0 - e.requestsLeft = 0 - e.lruPrev = 0 - e.lruNext = 0 + *e = entry{} } type limiter struct { diff --git a/ipratelimit/ipratelimit_test.go b/ipratelimit/ipratelimit_test.go index d013ad4..d7084a0 100644 --- a/ipratelimit/ipratelimit_test.go +++ b/ipratelimit/ipratelimit_test.go @@ -365,14 +365,14 @@ func TestDebugHTML(t *testing.T) { func BenchmarkDifferentIPv4_256(b *testing.B) { l := NewLimiter(1, time.Second, 256) - for i := 0; i < b.N; i++ { + for i := 0; b.Loop(); i++ { l.Allow(net.IPv4(byte(i>>24), byte(i>>16), byte(i>>8), byte(i))) } } func BenchmarkDifferentIPv4_10000(b *testing.B) { l := NewLimiter(1, time.Second, 10000) - for i := 0; i < b.N; i++ { + for i := 0; b.Loop(); i++ { l.Allow(net.IPv4(byte(i>>24), byte(i>>16), byte(i>>8), byte(i))) } } @@ -380,7 +380,7 @@ func BenchmarkDifferentIPv4_10000(b *testing.B) { func BenchmarkSameIPv4_Strict(b *testing.B) { l := NewLimiter(1, time.Second, 256) ip := net.IPv4(1, 2, 3, 4) - for i := 0; i < b.N; i++ { + for b.Loop() { l.Allow(ip) } } @@ -388,7 +388,7 @@ func BenchmarkSameIPv4_Strict(b *testing.B) { func BenchmarkSameIPv4_Bursty(b *testing.B) { l := NewLimiter(100, time.Second, 256) ip := net.IPv4(1, 2, 3, 4) - for i := 0; i < b.N; i++ { + for b.Loop() { l.Allow(ip) } } @@ -406,7 +406,7 @@ func BenchmarkSameIPv4_Strict_Parallel(b *testing.B) { func BenchmarkDifferentIPv6_256(b *testing.B) { l := NewLimiter(1, time.Second, 256) ip := net.ParseIP("1111:2222:3333:4444:5555:6666:7777:8888") - for i := 0; i < b.N; i++ { + for i := 0; b.Loop(); i++ { // Change the IP at different levels, so they don't all fall under the // same /64, /56, /48. ip[7] = byte(i) @@ -420,7 +420,7 @@ func BenchmarkDifferentIPv6_256(b *testing.B) { func BenchmarkDifferentIPv6_10000(b *testing.B) { l := NewLimiter(1, time.Second, 10000) ip := net.ParseIP("1111:2222:3333:4444:5555:6666:7777:8888") - for i := 0; i < b.N; i++ { + for i := 0; b.Loop(); i++ { ip[7] = byte(i) ip[6] = byte(i >> 8) ip[5] = byte(i) @@ -432,7 +432,7 @@ func BenchmarkDifferentIPv6_10000(b *testing.B) { func BenchmarkSameIPv6_Strict(b *testing.B) { l := NewLimiter(1, time.Second, 256) ip := net.ParseIP("1111:2222:3333:4444:5555:6666:7777:8888") - for i := 0; i < b.N; i++ { + for b.Loop() { l.Allow(ip) } } @@ -440,7 +440,7 @@ func BenchmarkSameIPv6_Strict(b *testing.B) { func BenchmarkSameIPv6_Bursty(b *testing.B) { l := NewLimiter(100, time.Second, 256) ip := net.ParseIP("1111:2222:3333:4444:5555:6666:7777:8888") - for i := 0; i < b.N; i++ { + for b.Loop() { l.Allow(ip) } } diff --git a/nettrace/bench_test.go b/nettrace/bench_test.go index e6430e2..e8713bf 100644 --- a/nettrace/bench_test.go +++ b/nettrace/bench_test.go @@ -39,7 +39,7 @@ func BenchmarkTrace_10000(b *testing.B) { } func BenchmarkNewAndFinish(b *testing.B) { - for i := 0; i < b.N; i++ { + for b.Loop() { tr := New("bench", "test") tr.Finish() } @@ -48,8 +48,7 @@ func BenchmarkNewAndFinish(b *testing.B) { func BenchmarkPrintf(b *testing.B) { tr := New("bench", "test") defer tr.Finish() - b.ResetTimer() - for i := 0; i < b.N; i++ { + for b.Loop() { // Keep this without any formatting, so we measure our code instead of // the performance of fmt.Sprintf. tr.Printf("this is printf") @@ -59,8 +58,7 @@ func BenchmarkPrintf(b *testing.B) { func BenchmarkPrint(b *testing.B) { tr := New("bench", "test") defer tr.Finish() - b.ResetTimer() - for i := 0; i < b.N; i++ { + for b.Loop() { tr.Print("this is print") } } diff --git a/nettrace/http.go b/nettrace/http.go index 2f51acc..c490c5b 100644 --- a/nettrace/http.go +++ b/nettrace/http.go @@ -8,7 +8,7 @@ import ( "html/template" "math" "net/http" - "sort" + "slices" "strconv" "time" ) @@ -156,8 +156,8 @@ func allEvents(tr *trace) []traceAndEvent { evts := appendAllEvents(tr, []traceAndEvent{}, seen, 0) // Sort them by time. - sort.Slice(evts, func(i, j int) bool { - return evts[i].Event.When.Before(evts[j].Event.When) + slices.SortStableFunc(evts, func(a, b traceAndEvent) int { + return a.Event.When.Compare(b.Event.When) }) return evts diff --git a/nettrace/trace.go b/nettrace/trace.go index 39f3ea0..a348849 100644 --- a/nettrace/trace.go +++ b/nettrace/trace.go @@ -7,7 +7,7 @@ import ( "fmt" "maps" "math/rand/v2" - "sort" + "slices" "strconv" "strings" "sync" @@ -216,9 +216,7 @@ func (tr *trace) Link(other Trace, msg string) { func (tr *trace) SetMaxEvents(n int) { // Set a minimum of 6, so the truncation works without running into // issues. - if n < 6 { - n = 6 - } + n = max(n, 6) tr.mu.Lock() tr.maxEvents = n tr.cutoff = n / 3 @@ -454,8 +452,8 @@ func (ft *familyTraces) TracesFor(b int, allgt bool) []*trace { // Sort them by start, newer first. This is the order that will be used // when displaying them. - sort.Slice(trs, func(i, j int) bool { - return trs[i].Start.After(trs[j].Start) + slices.SortFunc(trs, func(a, b *trace) int { + return b.Start.Compare(a.Start) }) return trs } diff --git a/ratelimit/ratelimit.go b/ratelimit/ratelimit.go index 35d7723..61ab7af 100644 --- a/ratelimit/ratelimit.go +++ b/ratelimit/ratelimit.go @@ -2,8 +2,9 @@ package ratelimit import ( "fmt" + "maps" "net/http" - "sort" + "slices" "blitiri.com.ar/go/gofer/config" "blitiri.com.ar/go/gofer/ipratelimit" @@ -42,7 +43,6 @@ func FromConfig(name string, conf config.RateLimit) { log.Infof("ratelimit %q: %d/%s, size %d", name, conf.Rate.Requests, conf.Rate.Period, conf.Size) - return } func FromName(name string) *ipratelimit.Limiter { @@ -54,11 +54,7 @@ func Trace(rl *ipratelimit.Limiter) *trace.Trace { } func DebugHandler(w http.ResponseWriter, r *http.Request) { - names := []string{} - for name := range registry { - names = append(names, name) - } - sort.Strings(names) + names := slices.Sorted(maps.Keys(registry)) fmt.Fprintf(w, `<!DOCTYPE html> <html> diff --git a/server/auth.go b/server/auth.go index 7e923d3..a22cc5c 100644 --- a/server/auth.go +++ b/server/auth.go @@ -80,7 +80,6 @@ func (a *AuthWrapper) success(w http.ResponseWriter, r *http.Request, user strin func (a *AuthWrapper) failed(w http.ResponseWriter) { w.Header().Set("WWW-Authenticate", `Basic realm="Authentication"`) http.Error(w, "Unauthorized", http.StatusUnauthorized) - return } type userCtxKey struct{} diff --git a/server/fileserver.go b/server/fileserver.go index 60f943e..118228f 100644 --- a/server/fileserver.go +++ b/server/fileserver.go @@ -1,12 +1,13 @@ package server import ( + "errors" "html" "net/http" "net/url" "os" "path" - "sort" + "slices" "strconv" "strings" "text/template" @@ -15,15 +16,11 @@ import ( // FileServer implements an equivalent of http.FileServer, but with custom // directory listing. func FileServer(root http.FileSystem) http.Handler { - return &fileServer{ - root: root, - upsrv: http.FileServer(root), - } + return &fileServer{root: root} } type fileServer struct { - root http.FileSystem - upsrv http.Handler + root http.FileSystem } func (fsrv *fileServer) ServeHTTP(w http.ResponseWriter, req *http.Request) { @@ -103,17 +100,16 @@ func localRedirect(w http.ResponseWriter, req *http.Request, dst string) { } func toHTTPError(w http.ResponseWriter, err error) { - if os.IsNotExist(err) { + if errors.Is(err, os.ErrNotExist) { http.Error(w, "404 Not found", http.StatusNotFound) return } - if os.IsPermission(err) { + if errors.Is(err, os.ErrPermission) { http.Error(w, "403 Forbidden", http.StatusForbidden) return } http.Error(w, "500 Internal Server Error", http.StatusInternalServerError) - return } func dirList(w http.ResponseWriter, req *http.Request, f http.File) { @@ -124,7 +120,7 @@ func dirList(w http.ResponseWriter, req *http.Request, f http.File) { } // Sort the entries by name. - sort.Slice(dirs, func(i, j int) bool { return dirs[i].Name() < dirs[j].Name() }) + slices.SortFunc(dirs, func(a, b os.FileInfo) int { return strings.Compare(a.Name(), b.Name()) }) w.Header().Set("Content-Type", "text/html; charset=utf-8") diff --git a/server/http.go b/server/http.go index d0019fb..fa31f69 100644 --- a/server/http.go +++ b/server/http.go @@ -49,7 +49,7 @@ func httpServer(addr string, conf config.HTTP) (*http.Server, error) { mux.Handle(path, makeDir(path, r.Dir, r.DirOpts)) } else if r.File != "" { log.Infof("%s route %q -> file %q", srv.Addr, path, r.File) - mux.Handle(path, makeFile(path, r.File)) + mux.Handle(path, makeFile(r.File)) } else if r.Proxy != nil { log.Infof("%s route %q -> proxy %s", srv.Addr, path, r.Proxy) mux.Handle(path, makeProxy(path, r.Proxy.URL())) @@ -65,7 +65,7 @@ func httpServer(addr string, conf config.HTTP) (*http.Server, error) { mux.Handle(path, makeCGI(path, r.CGI)) } else if r.Status > 0 { log.Infof("%s route %q -> status %d", srv.Addr, path, r.Status) - mux.Handle(path, makeStatus(path, r.Status)) + mux.Handle(path, makeStatus(r.Status)) } } @@ -306,7 +306,7 @@ func makeDir(path string, dir string, opts config.DirOpts) http.Handler { }) } -func makeFile(path string, file string) http.Handler { +func makeFile(file string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { tr, _ := trace.FromContext(r.Context()) tr.Printf("serving file %q", file) @@ -371,7 +371,7 @@ func makeRedirectRe(rxs []config.RePair) http.Handler { }) } -func makeStatus(from string, status int) http.Handler { +func makeStatus(status int) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { tr, _ := trace.FromContext(r.Context()) tr.Printf("status %d", status) diff --git a/server/peruser_test.go b/server/peruser_test.go index 386df79..b3617d0 100644 --- a/server/peruser_test.go +++ b/server/peruser_test.go @@ -1,6 +1,7 @@ package server import ( + "errors" "io" "net/http" "net/http/httptest" @@ -113,7 +114,7 @@ func TestPerUserDir(t *testing.T) { if resp.StatusCode != http.StatusForbidden { t.Errorf("anon PUT: status = %d, want 403", resp.StatusCode) } - if _, err := os.Stat(filepath.Join(root, "anon.txt")); !os.IsNotExist(err) { + if _, err := os.Stat(filepath.Join(root, "anon.txt")); !errors.Is(err, os.ErrNotExist) { t.Errorf("anon PUT wrote a file outside any user directory") } @@ -133,7 +134,7 @@ func TestPerUserDir(t *testing.T) { if resp.StatusCode != http.StatusNoContent { t.Errorf("alice DELETE: status = %d, want 204", resp.StatusCode) } - if _, err := os.Stat(filepath.Join(root, "alice", "f.txt")); !os.IsNotExist(err) { + if _, err := os.Stat(filepath.Join(root, "alice", "f.txt")); !errors.Is(err, os.ErrNotExist) { t.Errorf("alice file still exists after DELETE") } if _, err := os.Stat(filepath.Join(root, "bob", "f.txt")); err != nil { diff --git a/server/server_test.go b/server/server_test.go index 1a5db59..62aa273 100644 --- a/server/server_test.go +++ b/server/server_test.go @@ -3,7 +3,6 @@ package server import ( "fmt" "io" - "io/ioutil" "net" "net/http" "net/http/httptest" @@ -154,7 +153,7 @@ func testGet(t *testing.T, url string, expectedStatus int) { return } - b, err := ioutil.ReadAll(resp.Body) + b, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } @@ -343,7 +342,7 @@ func Benchmark(b *testing.B) { return func(b *testing.B) { var resp *http.Response var err error - for i := 0; i < b.N; i++ { + for b.Loop() { resp, err = http.Get(url) if err != nil { b.Fatal(err) diff --git a/test/util/exp/exp.go b/test/util/exp/exp.go index 9fada7d..fbc867e 100644 --- a/test/util/exp/exp.go +++ b/test/util/exp/exp.go @@ -2,16 +2,18 @@ package main import ( + "context" "crypto/tls" "crypto/x509" "flag" "fmt" - "io/ioutil" + "io" + "maps" "net" "net/http" "os" "regexp" - "sort" + "slices" "strconv" "strings" ) @@ -67,7 +69,7 @@ func main() { Transport: mkTransport(*caCert, *forceLocalhost), } - var bodyReader *strings.Reader + var bodyReader io.Reader if *reqBody != "" { s, err := strconv.Unquote("\"" + *reqBody + "\"") if err != nil { @@ -75,13 +77,7 @@ func main() { } bodyReader = strings.NewReader(s) } - var req *http.Request - var err error - if bodyReader == nil { - req, err = http.NewRequest(*method, url, nil) - } else { - req, err = http.NewRequest(*method, url, bodyReader) - } + req, err := http.NewRequest(*method, url, bodyReader) if err != nil { fatalf("error building request: %v\n", err) } @@ -110,7 +106,7 @@ func main() { fatalf("error getting %q: %v\n", url, err) } defer resp.Body.Close() - rbody, err := ioutil.ReadAll(resp.Body) + rbody, err := io.ReadAll(resp.Body) if err != nil { errorf("error reading body: %v\n", err) } @@ -119,12 +115,7 @@ func main() { fmt.Printf("Request: %s\n", url) fmt.Printf("Response:\n") fmt.Printf(" %v %v\n", resp.Proto, resp.Status) - ks := []string{} - for k, _ := range resp.Header { - ks = append(ks, k) - } - sort.Strings(ks) - for _, k := range ks { + for _, k := range slices.Sorted(maps.Keys(resp.Header)) { fmt.Printf(" %v: %s\n", k, strings.Join(resp.Header.Values(k), ", ")) } @@ -233,9 +224,10 @@ func mkTransport(caCert string, forceLocalhost bool) *http.Transport { } if forceLocalhost { - t.Dial = func(network, addr string) (net.Conn, error) { + t.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { _, port, _ := net.SplitHostPort(addr) - return net.Dial(network, "localhost:"+port) + var d net.Dialer + return d.DialContext(ctx, network, "localhost:"+port) } } diff --git a/util/util.go b/util/util.go index 7e1c88c..21a8abd 100644 --- a/util/util.go +++ b/util/util.go @@ -4,6 +4,7 @@ package util import ( "context" "crypto/tls" + "errors" "fmt" "io" "os" @@ -136,11 +137,11 @@ func LoadCertsFromDir(certDir string) (*tls.Config, error) { } certPath := filepath.Join(dir, "fullchain.pem") - if _, err := os.Stat(certPath); os.IsNotExist(err) { + if _, err := os.Stat(certPath); errors.Is(err, os.ErrNotExist) { continue } keyPath := filepath.Join(dir, "privkey.pem") - if _, err := os.Stat(keyPath); os.IsNotExist(err) { + if _, err := os.Stat(keyPath); errors.Is(err, os.ErrNotExist) { continue }