Skip to content

Instantly share code, notes, and snippets.

@vdparikh
Created September 7, 2023 17:31
Show Gist options
  • Save vdparikh/4efd73ca067c88473bfc31287ff8b880 to your computer and use it in GitHub Desktop.
Save vdparikh/4efd73ca067c88473bfc31287ff8b880 to your computer and use it in GitHub Desktop.
Insurance Policy Management
package main
import (
"github.com/gin-gonic/gin"
"net/http"
"strconv"
)
// InsurancePolicy represents an insurance policy.
type InsurancePolicy struct {
ID int `json:"id"`
Policyholder string `json:"policyholder"`
StartDate string `json:"start_date"`
EndDate string `json:"end_date"`
PremiumAmount float64 `json:"premium_amount"`
}
var policyIDCounter = 1
var policies = make(map[int]InsurancePolicy)
func main() {
r := gin.Default()
r.GET("/policies/:id", getPolicy)
r.POST("/policies", createPolicy)
r.PUT("/policies/:id", updatePolicy)
r.DELETE("/policies/:id", deletePolicy)
r.GET("/policies", listPolicies)
r.GET("/totalpremium", calculateTotalPremium)
r.Run(":8080")
}
func getPolicy(c *gin.Context) {
idParam := c.Param("id")
id, err := strconv.Atoi(idParam)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Policy ID"})
return
}
policy, exists := policies[id]
if !exists {
c.JSON(http.StatusNotFound, gin.H{"error": "Policy not found"})
return
}
c.JSON(http.StatusOK, policy)
}
func createPolicy(c *gin.Context) {
var policy InsurancePolicy
if err := c.ShouldBindJSON(&policy); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
policy.ID = policyIDCounter
policies[policyIDCounter] = policy
policyIDCounter++
c.JSON(http.StatusCreated, policy)
}
func updatePolicy(c *gin.Context) {
idParam := c.Param("id")
id, err := strconv.Atoi(idParam)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Policy ID"})
return
}
var policy InsurancePolicy
if err := c.ShouldBindJSON(&policy); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if _, exists := policies[id]; !exists {
c.JSON(http.StatusNotFound, gin.H{"error": "Policy not found"})
return
}
policy.ID = id
policies[id] = policy
c.JSON(http.StatusOK, policy)
}
func deletePolicy(c *gin.Context) {
idParam := c.Param("id")
id, err := strconv.Atoi(idParam)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Policy ID"})
return
}
if _, exists := policies[id]; !exists {
c.JSON(http.StatusNotFound, gin.H{"error": "Policy not found"})
return
}
delete(policies, id)
c.JSON(http.StatusNoContent, nil)
}
func listPolicies(c *gin.Context) {
policyList := []InsurancePolicy{}
for _, policy := range policies {
policyList = append(policyList, policy)
}
c.JSON(http.StatusOK, policyList)
}
func calculateTotalPremium(c *gin.Context) {
totalPremium := 0.0
for _, policy := range policies {
totalPremium += policy.PremiumAmount
}
c.JSON(http.StatusOK, gin.H{"total_premium": totalPremium})
}
package main
import (
"fmt"
"strconv"
)
// InsurancePolicy represents an insurance policy.
type InsurancePolicy struct {
ID int
Policyholder string
StartDate string
EndDate string
PremiumAmount float64
}
var policyIDCounter = 1
var policies = make(map[int]InsurancePolicy)
func main() {
for {
fmt.Println("\nInsurance Policy Management")
fmt.Println("1. Add a New Policy")
fmt.Println("2. View Policy Details")
fmt.Println("3. List All Policies")
fmt.Println("4. Calculate Total Premium")
fmt.Println("5. Search for Policies")
fmt.Println("6. Exit")
fmt.Print("Enter your choice: ")
var choice int
_, err := fmt.Scan(&choice)
if err != nil {
fmt.Println("Invalid input. Please enter a valid choice.")
continue
}
switch choice {
case 1:
addPolicy()
case 2:
viewPolicy()
case 3:
listPolicies()
case 4:
calculateTotalPremium()
case 5:
searchPolicies()
case 6:
fmt.Println("Goodbye!")
return
default:
fmt.Println("Invalid choice. Please select a valid option.")
}
}
}
func addPolicy() {
fmt.Println("\nAdd a New Policy")
fmt.Print("Policyholder Name: ")
var policyholder string
_, _ = fmt.Scanln(&policyholder)
fmt.Print("Start Date: ")
var startDate string
_, _ = fmt.Scanln(&startDate)
fmt.Print("End Date: ")
var endDate string
_, _ = fmt.Scanln(&endDate)
fmt.Print("Premium Amount: ")
var premiumAmount float64
_, _ = fmt.Scanln(&premiumAmount)
policy := InsurancePolicy{
ID: policyIDCounter,
Policyholder: policyholder,
StartDate: startDate,
EndDate: endDate,
PremiumAmount: premiumAmount,
}
policies[policyIDCounter] = policy
policyIDCounter++
fmt.Println("Policy added successfully.")
}
func viewPolicy() {
fmt.Println("\nView Policy Details")
fmt.Print("Enter Policy ID: ")
var id int
_, err := fmt.Scan(&id)
if err != nil {
fmt.Println("Invalid input. Please enter a valid Policy ID.")
return
}
policy, exists := policies[id]
if !exists {
fmt.Println("Policy not found.")
return
}
fmt.Printf("Policy ID: %d\n", policy.ID)
fmt.Printf("Policyholder: %s\n", policy.Policyholder)
fmt.Printf("Start Date: %s\n", policy.StartDate)
fmt.Printf("End Date: %s\n", policy.EndDate)
fmt.Printf("Premium Amount: $%.2f\n", policy.PremiumAmount)
}
func listPolicies() {
fmt.Println("\nList All Policies")
for id, policy := range policies {
fmt.Printf("Policy ID: %d, Policyholder: %s\n", id, policy.Policyholder)
}
}
func calculateTotalPremium() {
fmt.Println("\nCalculate Total Premium")
totalPremium := 0.0
for _, policy := range policies {
totalPremium += policy.PremiumAmount
}
fmt.Printf("Total Premium Amount: $%.2f\n", totalPremium)
}
func searchPolicies() {
fmt.Println("\nSearch for Policies")
fmt.Print("Enter Policyholder Name: ")
var searchName string
_, _ = fmt.Scanln(&searchName)
fmt.Println("Matching Policies:")
for id, policy := range policies {
if policy.Policyholder == searchName {
fmt.Printf("Policy ID: %d, Policyholder: %s\n", id, policy.Policyholder)
}
}
}

Imagine you are designing a simple system for an insurance company to manage their insurance policies. Each insurance policy has the following attributes:

  • Policy ID (a unique identifier)
  • Policyholder Name
  • Policy Start Date
  • Policy End Date
  • Premium Amount

Your task is to create a simple API or a command-line program in a programming language of your choice (e.g., Python, Java, C#) to manage these insurance policies. You need to implement the following functionalities:

  1. Add a New Policy: Allow the user to add a new insurance policy to the system. Prompt the user to enter the policyholder's name, start date, end date, and premium amount. Generate a unique policy ID for each policy.
  2. View Policy Details: Allow the user to view the details of a policy by entering the policy ID. Display all the attributes of the policy.
  3. List All Policies: Display a list of all policies, including their IDs and policyholder names.
  4. Calculate Total Premium: Calculate and display the total premium amount for all policies.
  5. Search for Policies: Allow the user to search for policies by policyholder name and display all matching policies.

Your program should provide a simple menu-driven interface that allows the user to perform these operations. You don't need to worry about saving data to a database or file for this exercise; you can store the policies in memory as a data structure.

Ensure that your code is well-structured, follows best practices, and handles edge cases (e.g., handling invalid user input gracefully). You can choose to use object-oriented programming or a different approach based on your preference.

If using API, expect below endpoints

This Go program uses the Gin web framework to create a RESTful API with the following endpoints:

  • GET /policies/:id: Retrieve a policy by ID.
  • POST /policies: Create a new policy.
  • PUT /policies/:id: Update a policy by ID.
  • DELETE /policies/:id: Delete a policy by ID.
  • GET /policies: List all policies.
  • GET /totalpremium: Calculate the total premium amount for all policies.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment