我无法执行go程序。我发现此示例使用go实现斜杠命令:https://medium.com/@emilygoldfein/creating-slack-slash-commands-using-go-3cea3b3f0920
我能够构建并运行该程序,但是当我进入松弛状态并在松弛状态中输入/ weather 90210时,出现错误:/ weather失败,并显示错误“ dispatch_failed”,并且在 ngrok我收到错误:POST / receve 404 Not found
代码如下:
```package main
import (
"encoding/json"
"fmt"
"log"
"math"
"net/http"
"os"
"github.com/joho/godotenv"
"github.com/nlopes/slack"
)
// APIResponse maps to the JSON response from the Open Weather Map API
type APIResponse struct {
Summary []struct {
ID int `json:"id"`
Main string `json:"main"`
Description string `json:"description"`
Icon string `json:"icon"`
} `json:"weather"`
Weather struct {
Temp float64 `json:"temp"`
Humidity int `json:"humidity"`
Pressure int `json:"pressure"`
TempMin float64 `json:"temp_min"`
TempMax float64 `json:"temp_max"`
} `json:"main"`
Location string `json:"name"`
}
func main() {
// Load environment variables
err := godotenv.Load("environment.env")
if err != nil {
log.Fatal("Error loading .env file")
}
http.HandleFunc("/receive", slashCommandHandler)
fmt.Println("[INFO] Server listening")
http.ListenAndServe(":8080", nil)
}
func slashCommandHandler(w http.ResponseWriter, r *http.Request) {
s, err := slack.SlashCommandParse(r)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
if !s.ValidateToken(os.Getenv("SLACK_VERIFICATION_TOKEN")) {
w.WriteHeader(http.StatusUnauthorized)
return
}
switch s.Command {
case "/weather":
params := &slack.Msg{Text: s.Text}
zipCode := params.Text
// Generates API request URL with zip code and API key
url := fmt.Sprintf("https://api.openweathermap.org/data/2.5/weather?zip=%v&APPID=%v&units=imperial", zipCode, os.Getenv("API_KEY"))
req, err := http.NewRequest("GET", url, nil)
if err != nil {
log.Fatal(err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusOK {
apiResponse := &APIResponse{}
err = json.NewDecoder(resp.Body).Decode(&apiResponse)
if err != nil {
log.Fatal(err)
}
// Round temp to nearest integer
roundedTemp := math.Round(apiResponse.Weather.Temp)
response := fmt.Sprintf("The weather in %v is %v. The temperature is %v\u00B0 F.", apiResponse.Location, apiResponse.Summary[0].Description, roundedTemp)
w.Write([]byte(response))
}
default:
w.WriteHeader(http.StatusInternalServerError)
return
}
}```
我正在运行Go 1.14
这是我的ngrok输出: 〜%ngrok http 8080 ngrok by @inconshreveable(Ctrl + C退出)
在线会话状态
会话到期7小时58分钟
版本2.3.35
美国(美国)地区
Web界面http://127.0.0.1:4040
转发http://79a86735e3bf.ngrok.io-> http:// localhost:8080
转发https://79a86735e3bf.ngrok.io-> http:// localhost:8080
连接ttl opn rt1 rt5 p50 p90
0 1 0.00 0.00 0.00 0.00
未找到POST /接收404