Skip to content
Snippets Groups Projects
routes.go 2.33 KiB
Newer Older
Lucendio's avatar
Lucendio committed
package routing

import (
    "encoding/json"
gjahn's avatar
gjahn committed
    "strings"
gjahn's avatar
gjahn committed
    "html/template"
    "log"
    "bytes"
Lucendio's avatar
Lucendio committed
    f "github.com/gofiber/fiber/v2"
)


func SetRoutes( router *f.App, config *configuration.Config, healthiness *bool ){
gjahn's avatar
gjahn committed
    indexHtmlTemplate, err := template.New( "index" ).Parse( indexHtml )
    if err != nil {
        log.Fatal( err )
    }


Lucendio's avatar
Lucendio committed
    router.Get( "/", func( c *f.Ctx ) error {
gjahn's avatar
gjahn committed
        headers := c.GetReqHeaders()
        if ! strings.Contains( headers[ "Accept" ], "html" ) {
            c.Set( "Content-Type", "text/plain; charset=utf-8" )
            return c.SendString( "Hello, World!" )
        }

        data := indexHtmlData{
            Version: "",
            Color: "",
        }

        buffer := &bytes.Buffer{}
        err := indexHtmlTemplate.Execute( buffer, data )
        if err != nil {
            return err
        }

        c.Set( "Content-Type", "text/html; charset=utf-8" )
        return c.Send( buffer.Bytes() )
Lucendio's avatar
Lucendio committed
    })
gjahn's avatar
gjahn committed


    router.Get( "/health", func( c *f.Ctx ) error {
        type response struct {
gjahn's avatar
gjahn committed
            Status  string  `json:"status"  validate:"oneof=pass fail"`
gjahn's avatar
gjahn committed
        c.Set( "Content-Type", "application/health+json; charset=utf-8" )
gjahn's avatar
gjahn committed
        var res *response
        if *healthiness == false {
gjahn's avatar
gjahn committed
            res = &response{
                Status: "fail",
            }
            c.Status( http.StatusServiceUnavailable )
        } else {
gjahn's avatar
gjahn committed
            res = &response{
                Status: "pass",
            }
            c.Status( http.StatusOK )
        }

gjahn's avatar
gjahn committed
        resJson, err := json.Marshal( res )
        if err != nil {
            return err
        }
        return c.SendString( string( resJson ) )
    router.Get( "/env", func( c *f.Ctx ) error {
        c.Type( "txt", "utf-8" )

        if config.Environment == "production" {
            c.Status( http.StatusForbidden )
            return nil
        }

        for _, envVar := range os.Environ() {
            _, err := c.WriteString( fmt.Sprintln( envVar ) )
            if err != nil {
                c.Status( http.StatusInternalServerError )
                return err
            }
        }
        c.Status( http.StatusOK )

        return nil
    })


gjahn's avatar
gjahn committed
    router.Use( func( c *f.Ctx ) error {
gjahn's avatar
gjahn committed
    })
Lucendio's avatar
Lucendio committed
}