Mux 和 http.HandleFunc 都在为 Google App Engine 上的 helloworld 端点工作

Mux nor http.HandleFunc is working for even a helloworld endpoint on Google App Engine

我无法让名为 emptysuccess 的处理程序工作。我正在将 sendgrid 变成一个 appspot 微服务。迄今为止 致电

http://localhost:8080/emptysuccess

Returns

404 page not found

这种行为是真实的 dev_appserver.py,也是真实的 appspot.com。如何让 /emptysuccess 工作?

package sendmail

import (
    "fmt"
    "github.com/sendgrid/sendgrid-go"
    "net/http"
    "google.golang.org/appengine"
    "github.com/gorilla/mux"
    "google.golang.org/appengine/log"

)

func main() {
    r := mux.Router{}
    r.HandleFunc("/send", sendhardcoded)
    r.HandleFunc("/emptysuccess", emptysuccess)
    //appengine.Main() // Starts the server to receive requests
}

func emptysuccess(w http.ResponseWriter, r *http.Request) {
    fmt.Println(w, "Hello Success")

}

func sendhardcoded(w http.ResponseWriter, r *http.Request) {
    ctx := appengine.NewContext(r)

    log.Infof(ctx, "Running Sendhardcoded")
    request := sendgrid.GetRequest("SG.OYPDF6hA.zk_XibKbJEUVLQfrkY-SBu5FejFakeC9ODFv1bE", "/v3/mail/send", "https://api.sendgrid.com")
    request.Method = "POST"
    request.Body = []byte(` {
    "personalizations": [
        {
            "to": [
                {
                    "email": "darian.hickman@gmail.info"
                }
            ],
            "subject": "Sending with SendGrid is Fun"
        }
    ],
    "from": {
        "email": "darian.hickman@ccc.com"
    },
    "content": [
        {
            "type": "text/plain",
            "value": "and easy to do anywhere, even with Go"
        }
    ]
}`)
    response, err := sendgrid.API(request)
    if err != nil {
        log.Errorf(ctx, "Problems: %v" ,err)
    } else {
        fmt.Println(w, response.StatusCode)
        fmt.Println(w, response.Body)
        fmt.Println(w, response.Headers)
        fmt.Println(w, "Sendmail should have worked")
    }
}

还要确保所有请求都转到 go 应用程序,我的 app.yaml 是:

runtime: go
api_version: go1.9

handlers:

- url: /static
  static_dir: static

- url: /.*
  script: _go_app
  login: required
  secure: always

以下是最终奏效的方法: 1. 我像 mkopriva 指出的那样修复了多路复用器代码。 (注意:http.handleFunc 而不是 http.Handle 不起作用)。 2. 我不得不将 main() 更改为 init(),然后 App Engine 确认了我的多路复用器设置。

所以基本上我了解到 go app engine 本身无法处理多个处理程序并且我通过设置 mux 搞砸了。

工作代码:

package sendmail

import (
    "fmt"
    _"github.com/sendgrid/sendgrid-go"
    "net/http"
    "google.golang.org/appengine"
    "github.com/gorilla/mux"
    "google.golang.org/appengine/log"

)

func init() {
    r := mux.NewRouter()
    r.HandleFunc("/send", sendhardcoded)
    r.HandleFunc("/emptysuccess", emptysuccess)
    //appengine.Main() // Starts the server to receive requests
    http.Handle("/", r)
}

func emptysuccess(w http.ResponseWriter, r *http.Request) {
    fmt.Println(w, "Hello Success")

}

func sendhardcoded(w http.ResponseWriter, r *http.Request) {
    ctx := appengine.NewContext(r)

    log.Infof(ctx, "Running Sendhardcoded")

}