How to redirect URL Ajax Jquery in Golang?
Use http.Redirect.
To make sure this worked, I wrote a little program. It serves http with three endpoints:
- / - serve a simple web page
-
/api - redirect to
/real-api
- /real-api - respond with “you found me”
This structure gives me just enough to try things out. BTW, since I don’t normally use jQuery, I modified the ajax example from http://jquery.com. I ended up with the following little program:
package main
import (
"log"
"net/http"
)
const html = `
<html>
<head>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function use_api() {
$.ajax({
url: "/api",
success: function( result ) {
$( "#result" ).html( result );
}
});
}
</script>
</head>
<body>
<input type=button value="use api" onclick="use_api()"/>
<div id="result"></div>
</body>
</html>
`
func main() {
log.SetFlags(log.Lshortfile)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(html))
})
http.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/real-api", http.StatusFound)
})
http.HandleFunc("/real-api", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("you found me"))
})
log.Fatalln(http.ListenAndServe("localhost:8080", nil))
}
Hope this answers your question.
1 Like
Thanks nathan for your quick response, it works…
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.