|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "github.com/go-chi/chi/v5" |
| 5 | + "github.com/go-chi/chi/v5/middleware" |
| 6 | + "github.com/rluders/httpsuite/v2" |
| 7 | + "log" |
| 8 | + "net/http" |
| 9 | + "strconv" |
| 10 | +) |
| 11 | + |
| 12 | +type SampleRequest struct { |
| 13 | + ID int `json:"id" validate:"required"` |
| 14 | + Name string `json:"name" validate:"required,min=3"` |
| 15 | + Age int `json:"age" validate:"required,min=1"` |
| 16 | +} |
| 17 | + |
| 18 | +type SampleResponse struct { |
| 19 | + ID int `json:"id"` |
| 20 | + Name string `json:"name"` |
| 21 | + Age int `json:"age"` |
| 22 | +} |
| 23 | + |
| 24 | +func (r *SampleRequest) SetParam(fieldName, value string) error { |
| 25 | + switch fieldName { |
| 26 | + case "id": |
| 27 | + id, err := strconv.Atoi(value) |
| 28 | + if err != nil { |
| 29 | + return err |
| 30 | + } |
| 31 | + r.ID = id |
| 32 | + } |
| 33 | + return nil |
| 34 | +} |
| 35 | + |
| 36 | +func ChiParamExtractor(r *http.Request, key string) string { |
| 37 | + return chi.URLParam(r, key) |
| 38 | +} |
| 39 | + |
| 40 | +// You can test it using: |
| 41 | +// |
| 42 | +// curl -X POST http://localhost:8080/submit/123 \ |
| 43 | +// -H "Content-Type: application/json" \ |
| 44 | +// -d '{"name": "John Doe", "age": 30}' |
| 45 | +// |
| 46 | +// And you should get: |
| 47 | +// |
| 48 | +// {"data":{"id":123,"name":"John Doe","age":30}} |
| 49 | +func main() { |
| 50 | + // Creating the router with Chi |
| 51 | + r := chi.NewRouter() |
| 52 | + r.Use(middleware.Logger) |
| 53 | + r.Use(middleware.Recoverer) |
| 54 | + |
| 55 | + // Define the endpoint POST |
| 56 | + r.Post("/submit/{id}", func(w http.ResponseWriter, r *http.Request) { |
| 57 | + // Using the function for parameter extraction to the ParseRequest |
| 58 | + req, err := httpsuite.ParseRequest[*SampleRequest](w, r, ChiParamExtractor, "id") |
| 59 | + if err != nil { |
| 60 | + log.Printf("Error parsing or validating request: %v", err) |
| 61 | + return |
| 62 | + } |
| 63 | + |
| 64 | + resp := &SampleResponse{ |
| 65 | + ID: req.ID, |
| 66 | + Name: req.Name, |
| 67 | + Age: req.Age, |
| 68 | + } |
| 69 | + |
| 70 | + // Sending success response |
| 71 | + httpsuite.SendResponse[SampleResponse](w, http.StatusOK, *resp, nil, nil) |
| 72 | + }) |
| 73 | + |
| 74 | + // Starting the server |
| 75 | + log.Println("Starting server on :8080") |
| 76 | + http.ListenAndServe(":8080", r) |
| 77 | +} |
0 commit comments