Main Method: (Post Handler is looping)
func main() {
lg := log.New(os.Stdout, "slack-bot: ", log.Lshortfile|log.LstdFlags)
ctx := context.Background()
s, err := post.New()
if err != nil {
lg.Fatal(err)
}
s.Logger = lg
if err := s.Run(ctx); err != nil {
s.Logger.Fatal(err)
}
handler, err := s.NewHandler()
if err != nil {
s.Logger.Fatal(err)
}
port := os.Getenv("PORT")
if len(port) < 1 {
port = "8080"
}
fmt.Println("Listening on port", port)
http.ListenAndServe(":"+port, handler)
}
func (s *Slack) NewHandler() (http.Handler, error) {
r := chi.NewRouter()
r.Use(middleware.RequestID)
r.Use(middleware.RealIP)
r.Use(middleware.NoCache)
r.Use(middleware.Heartbeat("/ping"))
cors := cors.New(cors.Options{
AllowedOrigins: []string{"*"},
AllowedMethods: []string{"GET", "POST", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
AllowCredentials: true,
MaxAge: 300, // Maximum value not ignored by any of major browsers
})
r.Use(cors.Handler)
r.Get("/", indexHandler)
r.Post("/", postHandler)
r.Get("/debug/pprof/*", pprof.Index)
r.Get("/debug/vars", func(w http.ResponseWriter, r *http.Request) {
first := true
w.Header().Set("Content-Type", "application/json; charset=utf-8")
fmt.Fprintf(w, "{\n")
expvar.Do(func(kv expvar.KeyValue) {
if !first {
fmt.Fprintf(w, ",\n")
}
first = false
fmt.Fprintf(w, "%q: %s", kv.Key, kv.Value)
})
fmt.Fprintf(w, "\n}\n")
})
return r, nil
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("From INDEXHANDLER")
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(fmt.Sprintf("incorrect path: %s", r.URL.Path)))
return
}
switch r.Method {
case "GET":
fmt.Println("FROM CASE GET")
w.WriteHeader(http.StatusOK)
w.Write([]byte(fmt.Sprintf("%v", `¯\_(ツ)_/¯ GET`)))
return
case "POST":
fmt.Println("FROM CASE POST")
w.WriteHeader(http.StatusMovedPermanently)
w.Write([]byte("cannot post to this endpoint"))
return
default:
}
}
func postHandler(w http.ResponseWriter, r *http.Request) {
fmt.Println("In postHandler ***")
fmt.Println("r.Header", r.Header)
//fmt.Println("RESPONSE CODE FROM POSTHANDLER:", r.Response.StatusCode)
if r.URL.Path != "/" {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte(fmt.Sprintf("incorrect path: %s", r.URL.Path)))
return
}
if r.Body == nil {
w.WriteHeader(http.StatusNotAcceptable)
w.Write([]byte("empty body"))
return
}
defer r.Body.Close()
err := r.ParseForm()
if err != nil {
w.WriteHeader(http.StatusGone)
w.Write([]byte("could not parse body"))
return
}
}