diff --git a/.codacy.yml b/.codacy.yml index 1cb2822..5e6489c 100644 --- a/.codacy.yml +++ b/.codacy.yml @@ -9,4 +9,4 @@ exclude_paths: - "examples/**" - ".github/**" - "testdata/**" - - "**.md" \ No newline at end of file + - "**.md" diff --git a/examples/json/main.go b/examples/json/main.go new file mode 100644 index 0000000..5780dc2 --- /dev/null +++ b/examples/json/main.go @@ -0,0 +1,40 @@ +package main + +import ( + "net/http" + + "github.com/mojixcoder/kid" +) + +type MeRequest struct { + LastName string `json:"last_name"` +} + +type MeResponse struct { + FullName string `json:"full_name"` + Age int `json:"age"` +} + +func main() { + k := kid.New() + + k.Get("/me", meHandler) + + k.Run() +} + +func meHandler(c *kid.Context) { + var req MeRequest + + if err := c.ReadJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, kid.Map{"message": "invalid request body"}) + return + } + + me := MeResponse{ + FullName: "Mojix " + req.LastName, + Age: 23, + } + + c.JSON(http.StatusOK, me) +} diff --git a/examples/main.go b/examples/main.go deleted file mode 100644 index 84fce50..0000000 --- a/examples/main.go +++ /dev/null @@ -1,19 +0,0 @@ -package main - -import ( - "net/http" - - "github.com/mojixcoder/kid" -) - -func main() { - k := kid.New() - - k.Get("/hello", helloHandler) - - k.Run() -} - -func helloHandler(c *kid.Context) { - c.JSON(http.StatusOK, kid.Map{"message": "Hello Kid!"}) -} diff --git a/examples/path_parameters/main.go b/examples/path_parameters/main.go new file mode 100644 index 0000000..377f4f8 --- /dev/null +++ b/examples/path_parameters/main.go @@ -0,0 +1,31 @@ +package main + +import ( + "fmt" + "net/http" + + "github.com/mojixcoder/kid" +) + +func main() { + k := kid.New() + + k.Get("/greet/{name}", greetHandler) + + // It will be matched to any number of paramters. Including zero and one and so on. + k.Get("/path/{*starParam}", starParamHandler) + + k.Run() +} + +func greetHandler(c *kid.Context) { + name := c.Param("name") + + c.String(http.StatusOK, fmt.Sprintf("Hello %s!", name)) +} + +func starParamHandler(c *kid.Context) { + param := c.Param("starParam") + + c.String(http.StatusOK, fmt.Sprintf("Star path parameter: %q", param)) +} diff --git a/examples/simple/main.go b/examples/simple/main.go new file mode 100644 index 0000000..1d71fc9 --- /dev/null +++ b/examples/simple/main.go @@ -0,0 +1,19 @@ +package main + +import ( + "net/http" + + "github.com/mojixcoder/kid" +) + +func main() { + k := kid.New() + + k.Get("/greet", greetHandler) + + k.Run() +} + +func greetHandler(c *kid.Context) { + c.String(http.StatusOK, "Hello World!") +}