-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
65 lines (48 loc) · 1.18 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"encoding/hex"
"fmt"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
)
func hexHandler(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query()
hexColor := params.Get("hex")
// anything other than example query is invalid
if len(params) > 1 || !isValidHex(hexColor) {
http.Error(w, "Bad query, please use format: /convert?hex=ff0000", http.StatusBadRequest)
return
}
response := hexToRGB(hexColor)
fmt.Fprintf(w, "%s", response)
}
func isValidHex(h string) bool {
valid, _ := regexp.MatchString("^[0-9a-fA-F]{6}$", h)
return valid
}
func hexToRGB(h string) string {
decoded, _ := hex.DecodeString(h)
// convert decoded hex bytes to string
var hexStr = make([]string, len(decoded))
for i, e := range decoded {
hexStr[i] = strconv.Itoa(int(e))
}
rgb := "RGB(" + strings.Join(hexStr, ", ") + ")"
return rgb
}
func statusHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "OK")
}
func main() {
listenPort, ok := os.LookupEnv("LISTEN_PORT")
if !ok {
listenPort = "8080"
}
http.HandleFunc("/convert", hexHandler)
http.HandleFunc("/status", statusHandler)
log.Fatal(http.ListenAndServe(":"+listenPort, nil))
}