【发布时间】:2017-11-29 18:05:32
【问题描述】:
我有一个 Angular 前端应用程序和一个 golang api。角度应用程序已构建(并且运行良好)。它对调用外部服务的 go api 进行了几次调用。调用外部服务后,我希望前端重定向到成功页面。我似乎无法让它在我的 Go 代码中工作。
这就是我所拥有的(除了重定向之外也可以使用):
package main
import (
"github.com/gin-gonic/gin"
"github.com/gin-contrib/static"
"net/http"
"io/ioutil"
"strings"
"encoding/json"
"strconv"
"net/http/cookiejar"
)
const BASE_ENDPOINT = "https://external.host.com/"
const FIRST_CALL_ENDPOINT = BASE_ENDPOINT + "first"
const SECOND_CALL_ENDPOINT = BASE_ENDPOINT + "second"
func main() {
// create an http client with a cookie jar
cookieJar, _ := cookiejar.New(nil)
client := &http.Client{
Jar: cookieJar,
}
router := gin.Default()
// this is the default route for the front end. The angular app will handle
// all non-api calls
router.Use(static.Serve("/", static.LocalFile("../frontend/dist", true)))
// Routes
api := router.Group("/")
{
// get post calls to this endpoint
api.POST("/my/first", func(c *gin.Context) {
userData := c.PostForm("userData")
rawTextBody := "data=" + userData
resp, err := client.Post(FIRST_CALL_ENDPOINT, "text/plain", strings.NewReader(rawTextBody))
if err != nil {
panic(err)
}
body, _ := ioutil.ReadAll(resp.Body)
var data map[string]interface{}
jsonErr := json.Unmarshal([]byte(body), &data)
if jsonErr != nil {
panic(jsonErr)
}
// data comes back as a "float64", is converted to an int, then to a string
var jobId = strconv.Itoa(int(data["curjobId"].(float64)))
moreUserData := c.PostForm("moreUserData")
rawTextBodyCat := "secondUserData=" + moreUserData + "&jobid=" + jobId
_, secErr := client.Post(SECOND_CALL_ENDPOINT, "text/plain", strings.NewReader(rawTextBodyCat))
if secErr != nil {
panic(secErr)
}
// TODO: need "successfully submitted" page. This already exists in the frontend angular server
// I can manually go to that page. ('/my/success')
// what i've tried:
//http.Redirect(w, r, "/my/success", http.StatusSeeOther)
//http.RedirectHandler( "/my/success", http.StatusSeeOther)
})
}
router.NoRoute(func(c *gin.Context) {
c.File("../frontend/dist/index.html")
})
// Run server
router.Run(":8899")
}
在我的代码 cmets 中,您可以看到我已经尝试过 http.Redirect(w, r, "/my/success", http.StatusSeeOther),但我不知道如何在这种情况下调用它。我没有设置路由侦听器,而只是尝试按需触发重定向。这应该由角度应用程序以某种方式处理吗?如何告诉 Angular 应用程序“全部完成”?
【问题讨论】:
-
我认为解决方案是从 go 服务器返回 JSON,然后在 Angular 应用程序中处理重定向。