@@ -2,10 +2,13 @@ package progressbar
22
33import (
44 "bytes"
5+ "encoding/json"
56 "errors"
67 "fmt"
78 "io"
9+ "log"
810 "math"
11+ "net/http"
912 "os"
1013 "regexp"
1114 "strings"
@@ -1009,6 +1012,31 @@ func (p *ProgressBar) State() State {
10091012 return s
10101013}
10111014
1015+ // StartHTTPServer starts an HTTP server dedicated to serving progress bar updates. This allows you to
1016+ // display the status in various UI elements, such as an OS status bar with an `xbar` extension.
1017+ // It is recommended to run this function in a separate goroutine to avoid blocking the main thread.
1018+ //
1019+ // hostPort specifies the address and port to bind the server to, for example, "0.0.0.0:19999".
1020+ func (p * ProgressBar ) StartHTTPServer (hostPort string ) {
1021+ // for advanced users, we can return the data as json
1022+ http .HandleFunc ("/state" , func (w http.ResponseWriter , r * http.Request ) {
1023+ w .Header ().Set ("Content-Type" , "text/json" )
1024+ // since the state is a simple struct, we can just ignore the error
1025+ bs , _ := json .Marshal (p .State ())
1026+ w .Write (bs )
1027+ })
1028+ // for others, we just return the description in a plain text format
1029+ http .HandleFunc ("/desc" , func (w http.ResponseWriter , r * http.Request ) {
1030+ w .Header ().Set ("Content-Type" , "text/plain" )
1031+ fmt .Fprintf (w ,
1032+ "%d/%d, %.2f%%, %s left" ,
1033+ p .State ().CurrentNum , p .State ().Max , p .State ().CurrentPercent * 100 ,
1034+ (time .Second * time .Duration (p .State ().SecondsLeft )).String (),
1035+ )
1036+ })
1037+ log .Fatal (http .ListenAndServe (hostPort , nil ))
1038+ }
1039+
10121040// regex matching ansi escape codes
10131041var ansiRegex = regexp .MustCompile (`\x1b\[[0-9;]*[a-zA-Z]` )
10141042
0 commit comments