|
| 1 | +package main |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + |
| 7 | + "gofr.dev/examples/using-migrations/migrations" |
| 8 | + "gofr.dev/pkg/gofr" |
| 9 | +) |
| 10 | + |
| 11 | +const ( |
| 12 | + queryGetEmployee = "SELECT id,name,gender,contact_number,dob from employee where name = ?" |
| 13 | + queryInsertEmployee = "INSERT INTO employee (id, name, gender, contact_number,dob) values (?, ?, ?, ?, ?)" |
| 14 | +) |
| 15 | + |
| 16 | +func main() { |
| 17 | + // Create a new application |
| 18 | + a := gofr.New() |
| 19 | + |
| 20 | + // Add migrations to run |
| 21 | + a.Migrate(migrations.All()) |
| 22 | + |
| 23 | + // Add all the routes |
| 24 | + a.GET("/employee", GetHandler) |
| 25 | + a.POST("/employee", PostHandler) |
| 26 | + |
| 27 | + // Run the application |
| 28 | + a.Run() |
| 29 | +} |
| 30 | + |
| 31 | +type Employee struct { |
| 32 | + ID int `json:"id"` |
| 33 | + Name string `json:"name"` |
| 34 | + Gender string `json:"gender"` |
| 35 | + Phone int `json:"contact_number"` |
| 36 | + DOB string `json:"dob"` |
| 37 | +} |
| 38 | + |
| 39 | +// GetHandler handles GET requests for retrieving employee information |
| 40 | +func GetHandler(c *gofr.Context) (interface{}, error) { |
| 41 | + name := c.Param("name") |
| 42 | + if name == "" { |
| 43 | + return nil, errors.New("name can't be empty") |
| 44 | + } |
| 45 | + |
| 46 | + row := c.DB.QueryRowContext(c, queryGetEmployee, name) |
| 47 | + if row.Err() != nil { |
| 48 | + return nil, errors.New(fmt.Sprintf("DB Error : %v", row.Err())) |
| 49 | + } |
| 50 | + |
| 51 | + var emp Employee |
| 52 | + |
| 53 | + err := row.Scan(&emp.ID, &emp.Name, &emp.Gender, &emp.Phone, &emp.DOB) |
| 54 | + if err != nil { |
| 55 | + return nil, errors.New(fmt.Sprintf("DB Error : %v", err)) |
| 56 | + } |
| 57 | + |
| 58 | + return emp, nil |
| 59 | +} |
| 60 | + |
| 61 | +// PostHandler handles POST requests for creating new employees |
| 62 | +func PostHandler(c *gofr.Context) (interface{}, error) { |
| 63 | + var emp Employee |
| 64 | + if err := c.Bind(&emp); err != nil { |
| 65 | + c.Logger.Errorf("error in binding: %v", err) |
| 66 | + return nil, errors.New("invalid body") |
| 67 | + } |
| 68 | + |
| 69 | + // Execute the INSERT query |
| 70 | + _, err := c.DB.ExecContext(c, queryInsertEmployee, emp.ID, emp.Name, emp.Gender, emp.Phone, emp.DOB) |
| 71 | + |
| 72 | + if err != nil { |
| 73 | + return Employee{}, errors.New(fmt.Sprintf("DB Error : %v", err)) |
| 74 | + } |
| 75 | + |
| 76 | + return fmt.Sprintf("succesfully posted entity : %v", emp.Name), nil |
| 77 | +} |
0 commit comments