Redirect URL Ajax Jquery

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 I ended up with the following little program:

package main

import (

const html = `
<script src=""></script>
function use_api() {
		url: "/api",
		success: function( result ) {
			$( "#result" ).html( result );
<input type=button value="use api" onclick="use_api()"/>
<div id="result"></div>

func main() {

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

	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.