Golang connection to angularjs

How do I connect a backend server in go lang to angularjs? I know angularjs communicates with go via $http or $resource services but what part of the go code links communicates with angular once all the data structs have been made? Would this be the encoded/marshalled json or do we create some kind of route…

I am a newbie looking to start this project after studying angular and go but this is the part i don’t understand - what is the end point from go that angulars $resource or $http service links with?

You have to create your endpoint on the server.
Look at example_ServeMux_Handle for and example on how to create an endpoint.

After you understand that, you can have a look at frameworks that will help you build things much quickly, look for rest api golang or something similar on Google.

Here’s a very simple example I used for a talk on doing OAuth in AngularJS.
I used a Go server for the example. It’s hardly complete but it should give
you an idea. (It’s also a bit old, it uses Angular 1.3, but should still be
sufficient to give you the idea.)

Here’s how to use $http with JSON.

$http.post('/ajax', {
    Value: 'something',
}).success(function(data) {
    console.log("success!", data);
}).error(function(data) {
    console.log("error", data);
});
package main

import (
	"encoding/json"
	"log"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	var req struct {
		Value string
	}

	// decode the JSON received from angular
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		log.Println("error decoding JSON:", err)
		http.Error(w, "error decoding JSON", http.StatusBadRequest)
		return
	}

	// see "JSON Vulnerability Protection" at https://docs.angularjs.org/api/ng/service/$http
	if _, err := w.Write([]byte(")]}',\n")); err != nil {
		log.Println("error writing:", err)
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}

	var reply struct {
		Value string
	}

	// encode 'reply' to JSON and send to angular
	if err := json.NewEncoder(w).Encode(reply); err != nil {
		log.Println("error encoding JSON:", err)
		http.Error(w, "internal error", http.StatusInternalServerError)
		return
	}
}

func main() {
	http.HandleFunc("/ajax", handler)
	if err := http.ListenAndServe(":8088", nil); err != nil {
		log.Fatal(err)
	}
}

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.