library google chart

package main

import (
    "fmt"
    "net/http"
    "github.com/wcharczuk/go-chart/v2"
)

func main() {
    // Create a new slice to hold data points
    data := []chart.Value{
        {Value: 23, Label: "Apple"},
        {Value: 42, Label: "Banana"},
        {Value: 30, Label: "Cherry"},
    }

    // Create a new pie chart and set its properties
    pie := chart.PieChart{
        Width:  512,
        Height: 512,
        Values: data,
    }

    // Create an HTTP handler function to render the chart
    http.HandleFunc("/chart", func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "image/png")
        err := pie.Render(chart.PNG, w)
        if err != nil {
            fmt.Println("Error rendering pie chart: ", err)
        }
    })

    // Start an HTTP server on port 8080
    http.ListenAndServe(":8080", nil)
}

This Go code creates a simple pie chart using the "github.com/wcharczuk/go-chart/v2" library and serves it via an HTTP server on port 8080. Here's an explanation of each step:

  1. Import necessary packages:
  2. "fmt": for formatting and printing messages.
  3. "net/http": for handling HTTP requests and responses.
  4. "github.com/wcharczuk/go-chart/v2": the chart library used to create the pie chart.

  5. Define the main function.

  6. Create a slice named "data" to hold data points for the pie chart. Each data point consists of a value (numeric) and a label (string).

  7. Create a new pie chart object named "pie" and set its properties:

  8. Width and height: Dimensions of the chart.
  9. Values: The data slice containing the values and labels for the chart.

  10. Define an HTTP handler function using http.HandleFunc. This function will respond to requests made to the "/chart" endpoint.

  11. In the HTTP handler function:

  12. Set the response content type to "image/png" because we are going to render a PNG image.
  13. Use the pie.Render method to render the pie chart in PNG format and write it to the HTTP response. Any rendering errors are printed to the console.

  14. Start an HTTP server on port 8080 using http.ListenAndServe. This server listens for incoming requests and handles them by calling the appropriate HTTP handler function defined earlier.