-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
80 lines (70 loc) · 1.83 KB
/
main.go
File metadata and controls
80 lines (70 loc) · 1.83 KB
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
package main
import (
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/rluders/httpsuite/v3"
"github.com/rluders/httpsuite/validation/playground"
"log"
"net/http"
"strconv"
)
type SampleRequest struct {
ID int `json:"id" validate:"required"`
Name string `json:"name" validate:"required,min=3"`
Age int `json:"age" validate:"required,min=1"`
}
type SampleResponse struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
}
func (r *SampleRequest) SetParam(fieldName, value string) error {
switch fieldName {
case "id":
id, err := strconv.Atoi(value)
if err != nil {
return err
}
r.ID = id
}
return nil
}
func ChiParamExtractor(r *http.Request, key string) string {
return chi.URLParam(r, key)
}
// You can test it using:
//
// curl -X POST http://localhost:8080/submit/123 \
// -H "Content-Type: application/json" \
// -d '{"name": "John Doe", "age": 30}'
//
// And you should get:
//
// {"data":{"id":123,"name":"John Doe","age":30}}
func main() {
// Creating the router with Chi
r := chi.NewRouter()
r.Use(middleware.Logger)
r.Use(middleware.Recoverer)
httpsuite.SetValidator(playground.NewWithValidator(nil, &httpsuite.ProblemConfig{
BaseURL: "http://localhost:8080",
}))
// Define the endpoint POST
r.Post("/submit/{id}", func(w http.ResponseWriter, r *http.Request) {
req, err := httpsuite.ParseRequest[*SampleRequest](w, r, ChiParamExtractor, nil, "id")
if err != nil {
log.Printf("Error parsing or validating request: %v", err)
return
}
resp := &SampleResponse{
ID: req.ID,
Name: req.Name,
Age: req.Age,
}
// Sending success response
httpsuite.SendResponse[SampleResponse](w, http.StatusOK, *resp, nil, nil)
})
// Starting the server
log.Println("Starting server on :8080")
log.Fatal(http.ListenAndServe(":8080", r))
}