Skip to content

Commit

Permalink
Don't embed the data into Go files
Browse files Browse the repository at this point in the history
  • Loading branch information
leighmcculloch committed Dec 24, 2018
1 parent 3c55890 commit ba5b1cf
Show file tree
Hide file tree
Showing 10 changed files with 167 additions and 170 deletions.
4 changes: 0 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ deploy:
build:
cp *.yml website/data/
cp *.yml service/data/
embedfiles -out=service/shared/looks/yaml_files.go -pkg=looks looks.yml tags.yml
$(MAKE) -C website clean build

cdn:
Expand All @@ -17,6 +16,3 @@ cdn:
-H "X-Auth-Key: $(CLOUDFLARE_CLIENT_API_KEY)" \
-H "Content-Type: application/json" \
--data '{"purge_everything":true}'

setup:
go get 4d63.com/embedfiles
84 changes: 43 additions & 41 deletions service/commandlook.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,53 +13,55 @@ import (
"github.com/leighmcculloch/looks.wtf/service/shared/secrets"
)

func commandLookHandler(w http.ResponseWriter, r *http.Request) error {
c := r.Context()
defer r.Body.Close()
func commandLookHandler(dataLooks map[string][]looks.Look, dataTags []string) func(w http.ResponseWriter, r *http.Request) error {
return func(w http.ResponseWriter, r *http.Request) error {
c := r.Context()
defer r.Body.Close()

slackVerificationToken := secrets.Get(c, "SLACK_VERIFICATION_TOKEN")
slackVerificationToken := secrets.Get(c, "SLACK_VERIFICATION_TOKEN")

token := r.FormValue("token")
if token != slackVerificationToken {
http.Error(w, "401 Unauthorized", http.StatusUnauthorized)
return nil
}
token := r.FormValue("token")
if token != slackVerificationToken {
http.Error(w, "401 Unauthorized", http.StatusUnauthorized)
return nil
}

teamDomain := r.FormValue("team_domain")
channelName := r.FormValue("channel_name")
userID := r.FormValue("user_id")
command := r.FormValue("command")
tag := r.FormValue("text")
responseURL := r.FormValue("response_url")
teamDomain := r.FormValue("team_domain")
channelName := r.FormValue("channel_name")
userID := r.FormValue("user_id")
command := r.FormValue("command")
tag := r.FormValue("text")
responseURL := r.FormValue("response_url")

log.Printf("Request: TeamDomain: %s ChannelName: %s UserID: %s Command: %s Text: %s", teamDomain, channelName, userID, command, tag)
log.Printf("Request: TeamDomain: %s ChannelName: %s UserID: %s Command: %s Text: %s", teamDomain, channelName, userID, command, tag)

looksWithTag := looks.LooksWithTag(tag)
if len(looksWithTag) == 0 {
fmt.Fprintf(w, "Try using the /look command with one of these words: "+strings.Join(looks.Tags(), ", "))
return nil
}
looksWithTag := dataLooks[tag]
if len(looksWithTag) == 0 {
fmt.Fprintf(w, "Try using the /look command with one of these words: "+strings.Join(dataTags, ", "))
return nil
}

l := looksWithTag[rand.Intn(len(looksWithTag))]
l := looksWithTag[rand.Intn(len(looksWithTag))]

client := http.DefaultClient
body := bytes.Buffer{}
err := json.NewEncoder(&body).Encode(
slackCommandResponse{
ResponseType: "in_channel",
Text: fmt.Sprintf("<@%s>: %s", userID, l.Plain),
},
)
if err != nil {
return fmt.Errorf("Failed to make delayed response post to %s: %s", responseURL, err)
}
resp, err := client.Post(responseURL, "application/json", &body)
if err != nil {
return fmt.Errorf("Failed to make delayed response post to %s: %s", responseURL, err)
}
if resp.StatusCode != 200 {
return fmt.Errorf("Failed to make delayed response post to %s: status code returned is %d, want 200", responseURL, resp.StatusCode)
}
client := http.DefaultClient
body := bytes.Buffer{}
err := json.NewEncoder(&body).Encode(
slackCommandResponse{
ResponseType: "in_channel",
Text: fmt.Sprintf("<@%s>: %s", userID, l.Plain),
},
)
if err != nil {
return fmt.Errorf("Failed to make delayed response post to %s: %s", responseURL, err)
}
resp, err := client.Post(responseURL, "application/json", &body)
if err != nil {
return fmt.Errorf("Failed to make delayed response post to %s: %s", responseURL, err)
}
if resp.StatusCode != 200 {
return fmt.Errorf("Failed to make delayed response post to %s: status code returned is %d, want 200", responseURL, resp.StatusCode)
}

return nil
return nil
}
}
108 changes: 55 additions & 53 deletions service/commandlooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,69 +12,71 @@ import (
"github.com/leighmcculloch/looks.wtf/service/shared/secrets"
)

func commandLooksHandler(w http.ResponseWriter, r *http.Request) error {
c := r.Context()
defer r.Body.Close()
func commandLooksHandler(dataLooks map[string][]looks.Look, dataTags []string) func(w http.ResponseWriter, r *http.Request) error {
return func(w http.ResponseWriter, r *http.Request) error {
c := r.Context()
defer r.Body.Close()

slackVerificationToken := secrets.Get(c, "SLACK_VERIFICATION_TOKEN")
log.Printf(slackVerificationToken)
slackVerificationToken := secrets.Get(c, "SLACK_VERIFICATION_TOKEN")
log.Printf(slackVerificationToken)

token := r.FormValue("token")
if token != slackVerificationToken {
http.Error(w, "401 Unauthorized", http.StatusUnauthorized)
return nil
}
token := r.FormValue("token")
if token != slackVerificationToken {
http.Error(w, "401 Unauthorized", http.StatusUnauthorized)
return nil
}

teamDomain := r.FormValue("team_domain")
channelName := r.FormValue("channel_name")
userName := r.FormValue("user_name")
command := r.FormValue("command")
tag := r.FormValue("text")
teamDomain := r.FormValue("team_domain")
channelName := r.FormValue("channel_name")
userName := r.FormValue("user_name")
command := r.FormValue("command")
tag := r.FormValue("text")

log.Printf("Request: TeamDomain: %s ChannelName: %s UserName: %s Command: %s Text: %s", teamDomain, channelName, userName, command, tag)
log.Printf("Request: TeamDomain: %s ChannelName: %s UserName: %s Command: %s Text: %s", teamDomain, channelName, userName, command, tag)

looksWithTag := looks.LooksWithTag(tag)
if len(looksWithTag) == 0 {
fmt.Fprintf(w, "Try using the /look command with one of these words: "+strings.Join(looks.Tags(), ", "))
return nil
}
looksWithTag := dataLooks[tag]
if len(looksWithTag) == 0 {
fmt.Fprintf(w, "Try using the /look command with one of these words: "+strings.Join(dataTags, ", "))
return nil
}

maxLooks := 5
if maxLooks > len(looksWithTag) {
maxLooks = len(looksWithTag)
}
maxLooks := 5
if maxLooks > len(looksWithTag) {
maxLooks = len(looksWithTag)
}

actions := []slackCommandResponseAttachmentAction{}
for i := 0; i < maxLooks; i++ {
lookIdx := rand.Intn(len(looksWithTag))
actions := []slackCommandResponseAttachmentAction{}
for i := 0; i < maxLooks; i++ {
lookIdx := rand.Intn(len(looksWithTag))

l := looksWithTag[lookIdx]
actions = append(
actions,
slackCommandResponseAttachmentAction{
Name: "look",
Text: l.Plain,
Type: "button",
Value: l.Plain,
},
)
l := looksWithTag[lookIdx]
actions = append(
actions,
slackCommandResponseAttachmentAction{
Name: "look",
Text: l.Plain,
Type: "button",
Value: l.Plain,
},
)

looksWithTag = append(looksWithTag[:lookIdx], looksWithTag[lookIdx+1:]...)
}
looksWithTag = append(looksWithTag[:lookIdx], looksWithTag[lookIdx+1:]...)
}

w.Header().Add("Content-Type", "application/json")
response := slackCommandResponse{
ResponseType: "ephemeral",
Text: fmt.Sprintf("There are several looks tagged with `%s`.", tag),
Attachments: []slackCommandResponseAttachment{
{
Text: "Choose a look",
Fallback: "Oh no, something went wrong",
CallbackID: "looks",
Actions: actions,
w.Header().Add("Content-Type", "application/json")
response := slackCommandResponse{
ResponseType: "ephemeral",
Text: fmt.Sprintf("There are several looks tagged with `%s`.", tag),
Attachments: []slackCommandResponseAttachment{
{
Text: "Choose a look",
Fallback: "Oh no, something went wrong",
CallbackID: "looks",
Actions: actions,
},
},
},
}
enc := json.NewEncoder(w)
return enc.Encode(response)
}
enc := json.NewEncoder(w)
return enc.Encode(response)
}
4 changes: 4 additions & 0 deletions service/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,12 @@ module github.com/leighmcculloch/looks.wtf/service

require (
cloud.google.com/go v0.34.0
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57 // indirect
github.com/googleapis/gax-go v2.0.2+incompatible // indirect
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6 // indirect
go.opencensus.io v0.18.0 // indirect
golang.org/x/arch v0.0.0-20181203225421-5a4828bb7045 // indirect
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 // indirect
google.golang.org/api v0.0.0-20181221000618-65a46cafb132 // indirect
google.golang.org/appengine v1.4.0
google.golang.org/genproto v0.0.0-20181221175505-bd9b4fb69e2f // indirect
Expand Down
8 changes: 8 additions & 0 deletions service/go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@ github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfb
github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57 h1:eqyIo2HjKhKe/mJzTG8n4VqvLXIOEG+SLdDqX7xGtkY=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/googleapis/gax-go v2.0.2+incompatible h1:silFMLAnr330+NRuag/VjIGF7TLp/LBrV2CJKFLWEww=
github.com/googleapis/gax-go v2.0.2+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY=
github.com/grpc-ecosystem/grpc-gateway v1.5.0/go.mod h1:RSKVYQBd5MCa4OVpNdGskqpgL2+G+NZTnrVHpWWfpdw=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6 h1:UDMh68UUwekSh5iP2OMhRRZJiiBccgV7axzUG8vi56c=
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/openzipkin/zipkin-go v0.1.1/go.mod h1:NtoC/o8u3JlF1lSlyPNswIbeQH9bJTmOf0Erfk+hxe8=
Expand All @@ -23,6 +27,10 @@ github.com/prometheus/common v0.0.0-20180801064454-c7de2306084e/go.mod h1:daVV7q
github.com/prometheus/procfs v0.0.0-20180725123919-05ee40e3a273/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
go.opencensus.io v0.18.0 h1:Mk5rgZcggtbvtAun5aJzAtjKKN/t0R3jJPlWILlv938=
go.opencensus.io v0.18.0/go.mod h1:vKdFvxhtzZ9onBp9VKHK8z/sRpBMnKAsufL7wlDrCOA=
golang.org/x/arch v0.0.0-20181203225421-5a4828bb7045 h1:Pn8fQdvx+z1avAi7fdM2kRYWQNxGlavNDSyzrQg2SsU=
golang.org/x/arch v0.0.0-20181203225421-5a4828bb7045/go.mod h1:cYlCBUl1MsqxdiKgmc4uh7TxZfWSFLOGSRR090WDxt8=
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9 h1:mKdxBk7AujPs8kU4m80U72y/zjbZ3UcXC7dClwKbUI0=
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/lint v0.0.0-20180702182130-06c8688daad7/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225 h1:kNX+jCowfMYzvlSvJu5pQWEmyWFrBXJ3PBy10xKMXK8=
Expand Down
23 changes: 21 additions & 2 deletions service/app.go → service/main.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package main

import (
"io"
"log"
"net/http"
"os"

"github.com/leighmcculloch/looks.wtf/service/shared/looks"
)

type appHandler func(http.ResponseWriter, *http.Request) error
Expand All @@ -15,6 +18,22 @@ func (a appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
}

var dataLooks = looks.ParseLooks(func() io.Reader {
f, err := os.Open("data/looks.yml")
if err != nil {
panic(err)
}
return f
}())

var dataTags = looks.ParseTags(func() io.Reader {
f, err := os.Open("data/tags.yml")
if err != nil {
panic(err)
}
return f
}())

func main() {
port := os.Getenv("PORT")
if port == "" {
Expand All @@ -23,8 +42,8 @@ func main() {
addr := ":" + port

http.Handle("/oauth", appHandler(oauthHandler))
http.Handle("/command/look", appHandler(commandLookHandler))
http.Handle("/command/looks", appHandler(commandLooksHandler))
http.Handle("/command/look", appHandler(commandLookHandler(dataLooks, dataTags)))
http.Handle("/command/looks", appHandler(commandLooksHandler(dataLooks, dataTags)))
http.Handle("/action", appHandler(actionHandler))

log.Printf("Listening on %s", addr)
Expand Down
37 changes: 0 additions & 37 deletions service/shared/looks/load_looks.go

This file was deleted.

Loading

0 comments on commit ba5b1cf

Please sign in to comment.