From ce9cfb6deef990d5d39397953316ae4fe185c1b9 Mon Sep 17 00:00:00 2001 From: Wilfried OLLIVIER Date: Thu, 3 Mar 2022 15:46:43 +0100 Subject: [PATCH] Add result url in http response, pretty print if accepts text/plain --- application/home.go | 18 +----------------- application/task.go | 17 ++++++++++++++++- html/html.go | 17 +++++++++++++++++ 3 files changed, 34 insertions(+), 18 deletions(-) diff --git a/application/home.go b/application/home.go index 1ebf879..1aa021a 100644 --- a/application/home.go +++ b/application/home.go @@ -4,7 +4,6 @@ import ( "embed" "fmt" "net/http" - "strings" "github.com/factorysh/microdensity/html" "github.com/factorysh/microdensity/version" @@ -18,21 +17,6 @@ var ( homeTemplate string ) -func acceptsHTML(r *http.Request) bool { - accepts, found := r.Header["Accept"] - if !found { - return false - } - - for _, h := range accepts { - if strings.Contains(h, "text/html") { - return true - } - } - - return false -} - const logo = ` _ _ _ ___| |__ ___ ___| | __ _ __ ___ _ _ __ _____| |__ @@ -51,7 +35,7 @@ func (a *Application) HomeHandler() http.HandlerFunc { // if you ask for something that is not html // nice geeky ascii art - if !acceptsHTML(r) { + if !html.Accepts(r, "text/html") { w.Header().Set("content-type", "text/plain") w.Write([]byte(logo)) fmt.Fprintf(w, "Version: %s", version.Version()) diff --git a/application/task.go b/application/task.go index c6b079d..a88019c 100644 --- a/application/task.go +++ b/application/task.go @@ -9,6 +9,7 @@ import ( "net/http" "net/url" "os" + "strings" "time" "github.com/docker/docker/pkg/stdcopy" @@ -98,8 +99,22 @@ func (a *Application) PostTaskHandler(w http.ResponseWriter, r *http.Request) { l.Error("error when adding task", zap.String("task", t.Id.String()), zap.Error(err)) return } + + url := strings.Join([]string{a.Domain, "service", t.Service, t.Project, t.Branch, t.Commit, "volumes", "data", "result.html"}, "/") + + if html.Accepts(r, "text/plain") { + w.Header().Add("content-type", "text/plain") + _, err := w.Write([]byte(fmt.Sprintf("Result URL:\n\n\t\t%s\n\n", url))) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + w.Write([]byte(http.StatusText(http.StatusInternalServerError))) + } + return + } + render.JSON(w, r, map[string]string{ - "id": id.String(), + "id": id.String(), + "url": url, }) } diff --git a/html/html.go b/html/html.go index 8b0a97b..e3c76a4 100644 --- a/html/html.go +++ b/html/html.go @@ -6,6 +6,7 @@ import ( "html/template" _template "html/template" "net/http" + "strings" "github.com/yosssi/gohtml" ) @@ -76,3 +77,19 @@ func (c *Partial) Render() (_template.HTML, error) { return template.HTML(buffer.Bytes()), err } + +// Accepts checks is a request accept content of a specified kind +func Accepts(r *http.Request, kind string) bool { + accepts, found := r.Header["Accept"] + if !found { + return false + } + + for _, h := range accepts { + if strings.Contains(h, kind) { + return true + } + } + + return false +}