I'm fairly new with working with Golang and I came across an issue when trying to send back a JSON response.
My main.go code looks something like this:
import (
"github.com/gorilla/mux"
"github.com/justinas/alice"
)
mx.Handle("/verify", commonHandlers.ThenFunc(controller.VerifyHandler)).Methods("GET").Name("verify") // Used to display verify.html
mx.Handle("/verify", commonHandlers.ThenFunc(verifyUser)).Methods("GET") // I'm actually not certain if I can call 2 different function handlers on the same URL
My verifyHandler calls RenderTemplates, which looks something like this:
func RenderTemplates(w http.ResponseWriter, r *http.Request, name string) {
f, err := os.Open("./templates/" + name)
check(err)
defer f.Close()
buf, err := ioutil.ReadAll(f)
check(err)
fmt.Fprintf(w, string(buf))
}
RenderTemplates is used to display my verify.html page
Then I have the verifyUser function handler which sends back a JSON formatted response, which looks something like this:
response := generateResponse("Message goes here", false)
res, err := json.Marshal(response)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(res)
Then I have my AngularJS controller to make the request:
app.controller("verifyControl", ['$scope', '$http', function($scope, $http) {
$scope.message = "";
$http({
method: 'GET',
url: "/verify"
}).success(function(data) {
$scope.message = data.msg;
console.log(data);
});
}]);
The issue is the response that I get back from my AngularJS call is not JSON, instead it's the verify.html HTML page, which I assume came from verifyHandler. Is there a solution where I can get the JSON response?