aboutsummaryrefslogtreecommitdiff
path: root/app/handler.go
blob: 50de29ffe8bb3be9fecc33f5099cd2ebf4e3c223 (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
package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
	"regexp"
	"slices"
	"strconv"
	"strings"
)

var directory = ""

func init() {
	args := os.Args
	index := slices.Index(args, "--directory")
	if index > 0 {
		directory = args[index+1]
	}

	fmt.Println("directory: ", directory)
}

func basePathHandler(request *Request) *Response {
	return NewResponse(Ok, nil, nil)
}

func echoHandler(request *Request) *Response {
	message := strings.Split(request.Target(), "/")[2]
	return NewResponse(Ok, map[string]string{
		"Content-Type":   "text/plain",
		"Content-Length": strconv.Itoa(len(message)),
	}, []byte(message))
}

func userAgentHandler(request *Request) *Response {
	header := request.Header("User-Agent")
	return NewResponse(Ok, map[string]string{
		"Content-Type":   "text/plain",
		"Content-Length": strconv.Itoa(len(header)),
	}, []byte(header))
}

func fileHandler(request *Request) *Response {
	file, err := os.Open(filepath.Join(directory, strings.Split(request.Target(), "/")[2]))
	if err != nil {
		return NewResponse(NotFound, nil, nil)
	}

	buf, _ := io.ReadAll(file)
	return NewResponse(Ok, map[string]string{
		"Content-Type":   "application/octet-stream",
		"Content-Length": strconv.Itoa(len(buf)),
	}, buf)
}

func Register(builder *RouterBuilder) {
	builder.Add("GET", regexp.MustCompile("^/$"), basePathHandler)
	builder.Add("GET", regexp.MustCompile("^/echo/[a-zA-Z]+$"), echoHandler)
	builder.Add("GET", regexp.MustCompile("^/user-agent$"), userAgentHandler)

	if directory != "" {
		builder.Add("GET", regexp.MustCompile("^/files/.+$"), fileHandler)
	}
}