github.com/drone/runner-go@v1.12.0/handler/template/server.go (about) 1 // Copyright 2019 Drone.IO Inc. All rights reserved. 2 // Use of this source code is governed by the Polyform License 3 // that can be found in the LICENSE file. 4 5 // +build ignore 6 7 package main 8 9 import ( 10 "encoding/json" 11 "html/template" 12 "io/ioutil" 13 "log" 14 "net/http" 15 "path/filepath" 16 "regexp" 17 "strings" 18 "time" 19 ) 20 21 func main() { 22 addr := ":3333" 23 24 // serve templates with dummy data 25 http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 26 path := r.FormValue("data") 27 if path == "" { 28 http.Error(w, "missing data parameter", 500) 29 return 30 } 31 32 tmpl := r.FormValue("template") 33 if path == "" { 34 http.Error(w, "missing template parameter", 500) 35 return 36 } 37 38 // read the json data from file. 39 rawjson, err := ioutil.ReadFile(filepath.Join("testdata", path)) 40 if err != nil { 41 http.Error(w, "cannot open json file", 500) 42 return 43 } 44 45 // unmarshal the json data 46 data := map[string]interface{}{} 47 err = json.Unmarshal(rawjson, &data) 48 if err != nil { 49 http.Error(w, err.Error(), 500) 50 return 51 } 52 53 // load the templates 54 T := template.New("_").Funcs(funcMap) 55 matches, _ := filepath.Glob("files/*.tmpl") 56 for _, match := range matches { 57 raw, _ := ioutil.ReadFile(match) 58 base := filepath.Base(match) 59 T = template.Must( 60 T.New(base).Parse(string(raw)), 61 ) 62 } 63 64 // render the template 65 w.Header().Set("Content-Type", "text/html") 66 err = T.ExecuteTemplate(w, tmpl, data) 67 if err != nil { 68 log.Println(err) 69 } 70 }) 71 72 // serve static content. 73 http.Handle("/static/", 74 http.StripPrefix("/static/", 75 http.FileServer( 76 http.Dir("../static/files"), 77 ), 78 ), 79 ) 80 81 log.Printf("listening at %s", addr) 82 log.Fatalln(http.ListenAndServe(addr, nil)) 83 } 84 85 // regular expression to extract the pull request number 86 // from the git ref (e.g. refs/pulls/{d}/head) 87 var re = regexp.MustCompile("\\d+") 88 89 // mirros the func map in template.go 90 var funcMap = map[string]interface{}{ 91 "timestamp": func(v float64) string { 92 return time.Unix(int64(v), 0).UTC().Format("2006-01-02T15:04:05Z") 93 }, 94 "pr": func(s string) string { 95 return re.FindString(s) 96 }, 97 "sha": func(s string) string { 98 if len(s) > 8 { 99 s = s[:8] 100 } 101 return s 102 }, 103 "tag": func(s string) string { 104 return strings.TrimPrefix(s, "refs/tags/") 105 }, 106 "done": func(s string) bool { 107 return s != "pending" && s != "running" 108 }, 109 }