File: echo.go

package info (click to toggle)
golang-github-appleboy-gofight 2.1.2-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 212 kB
  • sloc: makefile: 50
file content (114 lines) | stat: -rw-r--r-- 2,177 bytes parent folder | download | duplicates (2)
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
package framework

import (
	"log"
	"net/http"

	"github.com/labstack/echo/v4"
)

type echoContent struct {
	Hello string `json:"hello"`
	Foo   string `json:"foo"`
	A     string `json:"a"`
	B     string `json:"b"`
	C     string `json:"c"`
	D     string `json:"d"`
}

// Binding from JSON
type echoJSONContent struct {
	A int `json:"a" binding:"required"`
	B int `json:"b" binding:"required"`
}

func echoHelloHandler() echo.HandlerFunc {
	return func(c echo.Context) error {
		return c.JSON(http.StatusOK, &echoContent{
			Hello: "world",
		})
	}
}

func echoTextHandler() echo.HandlerFunc {
	return func(c echo.Context) error {
		return c.String(http.StatusOK, "Hello World")
	}
}

func echoQueryHandler() echo.HandlerFunc {
	return func(c echo.Context) error {
		text := c.QueryParam("text")
		foo := c.QueryParam("foo")

		return c.JSON(http.StatusOK, &echoContent{
			Hello: text,
			Foo:   foo,
		})
	}
}

func echoPostFormHandler() echo.HandlerFunc {
	return func(c echo.Context) error {
		a := c.FormValue("a")
		b := c.FormValue("b")

		return c.JSON(http.StatusOK, &echoContent{
			A: a,
			B: b,
		})
	}
}

func echoJSONHandler() echo.HandlerFunc {
	return func(c echo.Context) error {
		json := new(echoJSONContent)
		err := c.Bind(json)

		if err != nil {
			log.Println(err)
		}

		return c.JSON(http.StatusOK, json)
	}
}

func echoPutHandler() echo.HandlerFunc {
	return func(c echo.Context) error {
		foo := c.FormValue("c")
		bar := c.FormValue("d")

		return c.JSON(http.StatusOK, &echoContent{
			C: foo,
			D: bar,
		})
	}
}

func echoDeleteHandler() echo.HandlerFunc {
	return func(c echo.Context) error {
		return c.JSON(http.StatusOK, &echoContent{
			Hello: "world",
		})
	}
}

// EchoEngine is echo router.
func EchoEngine() *echo.Echo {
	e := echo.New()

	e.GET("/hello", echoHelloHandler())
	e.GET("/text", echoTextHandler())
	e.GET("/query", echoQueryHandler())

	e.POST("/form", echoPostFormHandler())
	e.POST("/json", echoJSONHandler())
	e.PUT("/update", echoPutHandler())
	e.DELETE("/delete", echoDeleteHandler())

	e.PATCH("/patch", echoHelloHandler())
	e.OPTIONS("/options", echoHelloHandler())
	e.HEAD("/head", echoHelloHandler())

	return e
}