Skip to content
Snippets Groups Projects
Commit a42a3ae8 authored by gjahn's avatar gjahn
Browse files

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.
parent bf2ab576
No related branches found
No related tags found
1 merge request!1Add first unit test to verify index route
......@@ -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() )
})
......
......@@ -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 )
}
......
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
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment