]> Sergey Matveev's repositories - btrtrc.git/blob - internal/testutil/status_writer.go
5ce66c612865b98d5f12c302973aa3bc93d1ad8f
[btrtrc.git] / internal / testutil / status_writer.go
1 package testutil
2
3 import (
4         "fmt"
5         "io"
6         "net/http"
7         "sync"
8
9         "github.com/anacrolix/missinggo"
10 )
11
12 type StatusWriter interface {
13         WriteStatus(io.Writer)
14 }
15
16 // The key is the route pattern. The value is nil when the resource is
17 // released.
18 var (
19         mu  sync.Mutex
20         sws = map[string]StatusWriter{}
21 )
22
23 func ExportStatusWriter(sw StatusWriter, path string) (release func()) {
24         pattern := fmt.Sprintf("/%s/%s", missinggo.GetTestName(), path)
25         release = func() {
26                 mu.Lock()
27                 defer mu.Unlock()
28                 sws[pattern] = nil
29         }
30         mu.Lock()
31         defer mu.Unlock()
32         if curSw, ok := sws[pattern]; ok {
33                 if curSw != nil {
34                         panic(fmt.Sprintf("%q still in use", pattern))
35                 }
36                 sws[pattern] = sw
37                 return
38         }
39         http.HandleFunc(
40                 pattern,
41                 func(w http.ResponseWriter, r *http.Request) {
42                         sw := sws[pattern]
43                         if sw == nil {
44                                 http.NotFound(w, r)
45                                 return
46                         }
47                         sw.WriteStatus(w)
48                 },
49         )
50         sws[pattern] = sw
51         return
52 }