-
Notifications
You must be signed in to change notification settings - Fork 0
/
fiche.go
76 lines (65 loc) · 1.85 KB
/
fiche.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
package main
import (
"bufio"
"fmt"
"log"
"net"
"os"
"time"
"github.com/pilu/go-base62"
"github.com/spf13/viper"
)
func ficheInit() {
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", viper.Get("port")))
if err != nil {
// handle error
log.Fatalf("Could not bind to port: %d!", viper.Get("port"))
os.Exit(-1)
}
log.Printf("Server started listening on port: %d.", viper.Get("port"))
for {
conn, err := listener.Accept()
if err != nil {
log.Printf("Error on accepting connection!")
continue
}
go fiche(conn)
}
}
func fiche(conn net.Conn) {
remoteHost, err := net.LookupCNAME(conn.RemoteAddr().String())
if err != nil {
remoteHost = conn.RemoteAddr().String()
}
defer func() {
log.Printf("Closing connection to: %s (%s).\n", remoteHost, conn.RemoteAddr().String())
conn.Close()
}()
log.Printf("Incoming connection from: %s (%s).\n", remoteHost, conn.RemoteAddr().String())
conn.SetReadDeadline(time.Now().Add(time.Second * 5))
slug := base62.Encode(int(time.Now().UnixNano()))
slugFullpath := fmt.Sprintf("%s/%s", viper.GetString("output"), slug)
log.Printf("Writing file to %s", slugFullpath)
file, err := os.Create(slugFullpath)
if err != nil {
conn.Write([]byte(fmt.Sprintf("%s", "Internal server error - Please try again later...\n\n")))
log.Fatalf("Unable to create slug file: %s", slugFullpath)
return
}
scanner := bufio.NewScanner(conn)
for scanner.Scan() {
file.WriteString(scanner.Text())
file.Write([]byte("\n"))
conn.SetReadDeadline(time.Now().Add(time.Second * 5))
}
stat, _ := file.Stat()
if stat.Size() <= 0 {
file.Close()
log.Printf("0 bytes received, aborting...")
os.Remove(slugFullpath)
return
}
file.Close()
log.Printf("Wrote %d bytes to %s", stat.Size(), slugFullpath)
conn.Write([]byte(fmt.Sprintf("%s://%s/%s\r\n", viper.GetString("uriprefix"), viper.GetString("domain"), slug)))
}