~mendelmaleh/bin

bin/main.go -rw-r--r-- 3.6 KiB
2fc3ccd2Mendel E Try getting scheme from X-Forwarded-Proto 9 months ago
                                                                                
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
package main

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"math/rand"
	"net/http"
	"net/url"
	"strings"
	"time"
	"unicode"

	"git.sr.ht/~mendelmaleh/bin/base26"
	"github.com/pelletier/go-toml"
	"github.com/prologic/bitcask"
)

// This is for the random id generator, it ensures the id is 6 chars long.
// The limitation is that it won't generate more than 297m (diff) ids.
const (
	min  int = 26 * 26 * 26 * 26 * 26 // 11_881_376  // 26 ** 5
	max  int = min * 26               // 308_915_776 // 26 ** 6
	diff int = max - min              // 297_034_400
)

// Config struct
type Config struct {
	Bin struct {
		DB      string
		Addr    string
		Pattern string
	}
}

func main() {
	// get config
	doc, err := ioutil.ReadFile("config.toml")
	if err != nil {
		log.Panic(err)
	}

	// parse config
	config := Config{}
	err = toml.Unmarshal(doc, &config)
	if err != nil {
		log.Panic(err)
	}

	// setup db
	db, err := bitcask.Open(config.Bin.DB)
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// setup http server
	http.HandleFunc(config.Bin.Pattern,
		func(w http.ResponseWriter, r *http.Request) {
			Bin(w, r, db)
		},
	)

	// run
	log.Fatal(http.ListenAndServe(config.Bin.Addr, nil))
}

func isASCII(s string) bool {
	for _, r := range s {
		if r > unicode.MaxASCII {
			return false
		}
	}
	return true
}

// Bin is a pastebin service, it requires a bitcask kv store.
func Bin(w http.ResponseWriter, r *http.Request, b *bitcask.Bitcask) {
	id := r.FormValue("id")

	if r.Method == "GET" {
		// no file was requested
		if id == "" {
			fmt.Fprintln(w, "todo: instructions")
			return
		}

		// a file was requested
		buf, err := b.Get([]byte(id))
		if err != nil {
			if err == bitcask.ErrKeyNotFound {
				w.WriteHeader(http.StatusNotFound)
				fmt.Fprintf(w, "no bin with id %q\n", id)
				return
			}

			log.Print(err)
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintf(w, "error %T when retrieving bin.\n", err)
			return
		}

		w.Write(buf)
		return
	}

	if r.Method == "POST" {
		// if no id was passed
		if id == "" {
			// generate random int
			rand.Seed(time.Now().UnixNano())
			n := rand.Intn(diff) + min
			id = base26.Itoa(n)

			// ensure id is available
			for b.Has([]byte(id)) {
				id = ""
				n = rand.Intn(diff) + min
				id = base26.Itoa(n)
			}
		} else if b.Has([]byte(id)) {
			w.WriteHeader(http.StatusConflict)
			fmt.Fprintf(w, "id %s is already taken. try again!\n", id)
			return
		} else if len(id) > 32 || !isASCII(id) {
			w.WriteHeader(http.StatusBadRequest)
			fmt.Fprintf(w, "id %s is not valid. ensure it's all ASCII and under 32 chars.\n", id)
			return
		}

		// get file
		file, _, err := r.FormFile("file")
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintf(w, "error %T when retrieving file, try again.\n", err)
			return
		}
		defer file.Close()

		// copy file
		var buf bytes.Buffer
		_, err = io.Copy(&buf, file)
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintf(w, "error %T when retrieving file, try again.\n", err)
			return
		}

		// save file
		err = b.Put([]byte(id), buf.Bytes())
		if err != nil {
			log.Println(err)
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintf(w, "error %T when saving file, try again.\n", err)
			return
		}

		// return id
		u := url.URL{
			Host:   r.Host,
			Path:   "/", // todo: use config or dynamic
		}

		if v, ok := r.Header["X-Forwarded-Proto"]; ok {
			u.Scheme = strings.Join(v, "")
		} else {
			u.Scheme = "http"
		}

		q := url.Values{}
		q.Set("id", id)

		u.RawQuery = q.Encode()
		w.WriteHeader(http.StatusCreated)
		fmt.Fprintf(w, "%s\n", u.String())

		return
	}
}