From a42a3ae81b0d475e360f258722b76a5f1404c498 Mon Sep 17 00:00:00 2001 From: gjahn <gregor.jahn@bht-berlin.de> Date: Fri, 3 Nov 2023 01:24:10 +0100 Subject: [PATCH] Teach root path HTML Depending on whats in the accept request header, the root path either response with a plain text or some nice HTML. --- routing/routes.go | 30 +++++++++++++++++++++++++++++- routing/routes_test.go | 11 +++++++++-- routing/templates.go | 22 ++++++++++++++++++++++ 3 files changed, 60 insertions(+), 3 deletions(-) create mode 100644 routing/templates.go diff --git a/routing/routes.go b/routing/routes.go index b80eda1..9f9ac3c 100644 --- a/routing/routes.go +++ b/routing/routes.go @@ -4,7 +4,11 @@ import ( "encoding/json" "os" "fmt" + "strings" "net/http" + "html/template" + "log" + "bytes" "webservice/configuration" @@ -14,8 +18,32 @@ import ( func SetRoutes( router *f.App, config *configuration.Config, healthiness *bool ){ + indexHtmlTemplate, err := template.New( "index" ).Parse( indexHtml ) + if err != nil { + log.Fatal( err ) + } + + router.Get( "/", func( c *f.Ctx ) error { - return c.SendString( "Hello, World!" ) + 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() ) }) diff --git a/routing/routes_test.go b/routing/routes_test.go index f37924f..15b1e93 100644 --- a/routing/routes_test.go +++ b/routing/routes_test.go @@ -71,10 +71,17 @@ func TestIndexRoute( t *testing.T ){ router, _, _ := setup() req := ht.NewRequest( "GET", "/", nil ) - res, err := router.Test( req, -1 ) - + req.Header.Add( "Accept", "text/html" ) + res, _ := router.Test( req, -1 ) bodyContent, err := bodyToString( &res.Body ) assert.Nil( t, err ) + assert.Contains( t, bodyContent, "</html>" ) + assert.Contains( t, bodyContent, "<head>" ) + + req = ht.NewRequest( "GET", "/", nil ) + res, _ = router.Test( req, -1 ) + bodyContent, err = bodyToString( &res.Body ) + assert.Nil( t, err ) assert.Equal( t, "Hello, World!", bodyContent ) } diff --git a/routing/templates.go b/routing/templates.go new file mode 100644 index 0000000..5e06f29 --- /dev/null +++ b/routing/templates.go @@ -0,0 +1,22 @@ +package routing + + + +const indexHtml = ` + <!DOCTYPE html> + <html> + <head> + <meta charset="UTF-8"> + <title>Webservice</title> + </head> + <body> + <h1 style="color: {{ .Color }}">Hello World, again!</h1> + <p>Version: {{ .Version }}</p> + </body> + </html> +` + +type indexHtmlData struct { + Version string + Color string +} -- GitLab