diff --git a/routing/routes.go b/routing/routes.go index b80eda13b89706dd75565319d5c818347b1ef576..9f9ac3c6db9dcc1ff9cc5dd0aa320d544d74a3b2 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 f37924fa5750be46a135113252db71207b305625..15b1e93c3758ea10d634e42638924c8f18951392 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 0000000000000000000000000000000000000000..5e06f2960d8d134c37b76c371cfeb3965f5d793f --- /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 +}