aboutsummaryrefslogtreecommitdiff
path: root/app/handler.go
blob: 02f4b270a7aba0d40d463cb2d3105a6cf9b73537 (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
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 getFile(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 createFile(request *Request) *Response {
	fPath := filepath.Join(directory, strings.Split(request.Target(), "/")[2])
	fmt.Println("create file: ", fPath)

	file, err := os.Create(fPath)
	if err != nil {
		return NewResponse(InternalServerError, nil, nil)
	}

	defer file.Close()

	length, err := strconv.Atoi(request.Header("Content-Length"))
	if err != nil {
		return NewResponse(InternalServerError, nil, nil)
	}

	_, err = io.CopyN(file, request.Body(), int64(length))
	if err != nil {
		return NewResponse(InternalServerError, nil, nil)
	}

	return NewResponse(Created, nil, nil)
}

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/.+$"), getFile)
		builder.Add("POST", regexp.MustCompile("^/files/.+$"), createFile)
	}
}