Skip to content

Instantly share code, notes, and snippets.

@winebarrel
Created July 8, 2023 06:31
Show Gist options
  • Select an option

  • Save winebarrel/39ff48f3deafbb4446248f163028eee5 to your computer and use it in GitHub Desktop.

Select an option

Save winebarrel/39ff48f3deafbb4446248f163028eee5 to your computer and use it in GitHub Desktop.

Revisions

  1. winebarrel renamed this gist Jul 8, 2023. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. winebarrel created this gist Jul 8, 2023.
    56 changes: 56 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    package main

    import (
    "fmt"
    "net/http"
    "os"
    "strings"

    "github.com/gin-gonic/gin"
    "github.com/winebarrel/ddcost"
    )

    func newHandler(estimate bool) func(*gin.Context) {
    client := ddcost.NewClient(&ddcost.ClientOptions{
    APIKey: os.Getenv("DD_API_KEY"),
    APPKey: os.Getenv("DD_APP_KEY"),
    })

    return func(c *gin.Context) {
    var buf strings.Builder

    err := client.PrintHistoricalCostByOrg(&buf, &ddcost.PrintHistoricalCostByOrgOptions{
    View: "sub-org",
    Output: "csv",
    Estimate: estimate,
    })

    if err != nil {
    c.String(http.StatusInternalServerError, err.Error()+"\n")
    return
    }

    c.Writer.Header().Set("Content-Type", "text/csv")
    c.String(http.StatusOK, buf.String())
    }
    }

    func main() {
    r := gin.Default()

    r.GET("/", newHandler(false))
    r.GET("/estimate", newHandler(true))

    addr := os.Getenv("LISTEN")
    port := os.Getenv("PORT")

    if addr == "" {
    addr = "127.0.0.1"
    }

    if port == "" {
    port = "8080"
    }

    r.Run(fmt.Sprintf("%s:%s", addr, port))
    }