aboutsummaryrefslogtreecommitdiff
path: root/send_over_http.go
blob: 98b7e6e445d7bec1b24d063358b055347f6d75d6 (plain)
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package sendoverhttp

import (
	"fmt"
	"io/fs"
	"log"
	"net"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strconv"
)

// port is the IP port address to listen on.
const port = 8081

func preferredIP() (*net.IP, error) {
	ips, err := net.InterfaceAddrs()
	if err != nil {
		return nil, err
	}
	for _, addr := range ips {
		ipNet, ok := addr.(*net.IPNet)
		if !ok {
			continue
		}
		if ipNet.IP.IsLoopback() {
			continue
		}
		return &ipNet.IP, nil
	}
	return nil, nil
}

type Server struct {
	filepath string

	closeCh chan struct{}
	mr      *MultiRunner
}

type SingleFileDir string

func (s SingleFileDir) Open(name string) (http.File, error) {
	if name == "index.html" {
		return nil, fs.ErrNotExist
	}

	fp := string(s)
	stat, err := os.Stat(fp)
	if err != nil {
		return nil, err
	}
	if stat.IsDir() {
		return http.Dir(fp).Open(name)
	}

	switch name {
	case "/":
		return nil, os.ErrNotExist
	case "/" + filepath.Base(fp):
		return os.Open(fp)
	default:
		return nil, os.ErrNotExist

	}
}

func NewServer(fp string) *Server {
	return &Server{
		closeCh:  make(chan struct{}),
		filepath: fp,
		mr:       NewMultiRunner(),
	}
}

func (s *Server) Start() error {
	ip, err := preferredIP()
	if err != nil {
		return err
	}

	u := url.URL{
		Scheme: "http",
		Host:   fmt.Sprintf("%s:%d", ip, port),
	}
	if stat, _ := os.Stat(s.filepath); !stat.IsDir() {
		u.Path = filepath.Base(s.filepath)
	}

	qrCodeShower := NewTerminalQRShower(u.String())
	go s.mr.Run(qrCodeShower)

	httpRunner := NewRunner()
	httpSrv := &http.Server{
		Addr: ":" + strconv.Itoa(port),
	}

	var d http.FileSystem = http.Dir(s.filepath)
	if stat, _ := os.Stat(s.filepath); !stat.IsDir() {
		// Show user the name of the file
		d = SingleFileDir(s.filepath)
	}
	httpSrv.Handler = http.FileServer(d)

	httpRunner.OnStart = func() error {
		l, err := net.Listen("tcp4", u.Host)
		if err != nil {
			log.Fatal(err)
		}
		return httpSrv.Serve(l)
	}
	httpRunner.OnStop = func() {
		_ = httpSrv.Close()
	}
	go s.mr.Run(httpRunner)

	<-s.closeCh
	close(s.closeCh)
	return nil
}

func (s *Server) Stop() {
	s.mr.Stop()
	return
}