-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
81 lines (68 loc) · 1.59 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
"net"
"os"
"os/signal"
"syscall"
)
const programName = "glimpse"
func main() {
ctx := context.Background()
code, err := run(ctx, os.Args[1:])
if err != nil {
fmt.Fprintf(os.Stderr, "%s: %v\n", programName, err)
}
os.Exit(code)
}
func run(ctx context.Context, args []string) (int, error) {
flag.CommandLine.Init(programName, flag.ContinueOnError)
var (
bindFlag = flag.String("b", ":1080", "Address to listen on")
userFlag = flag.String("u", "", "Proxy user")
passwdFlag = flag.String("p", "", "Proxy password")
)
if err := flag.CommandLine.Parse(args); err != nil {
code := 2
if errors.Is(err, flag.ErrHelp) {
code = 0
}
return code, nil
}
// Username without a password is invalid configuration, but password without a username is.
if *userFlag != "" && *passwdFlag == "" {
return 2, errors.New("password must not be empty when -u is used")
}
ctx, stop := signal.NotifyContext(ctx, syscall.SIGINT, syscall.SIGTERM)
defer stop()
ln, err := net.Listen("tcp", *bindFlag)
if err != nil {
return 1, err
}
defer ln.Close()
var opts []serverOpt
if *userFlag != "" || *passwdFlag != "" {
opts = append(opts, withPasswordAuth(*userFlag, *passwdFlag))
}
var (
srv = newServer(opts...)
errCh = make(chan error, 1)
)
go func() {
log.Printf("Listening on %s\n", ln.Addr())
if err := srv.Serve(ln); err != nil && !errors.Is(err, net.ErrClosed) {
errCh <- err
}
}()
select {
case <-ctx.Done():
case err := <-errCh:
return 1, err
}
log.Println("Shutting down...")
return 0, nil
}