I have a Go rest service that works fine, I can get form data using a Chrome REST plugin. I need to get form data from my Angular app to the service, and so far I cannot figure it out.
My Angular code:
<form name="myForm">
<div class="control-group" ng-class="{error: myForm.name.$invalid}">
<label>Drug Name</label>
<input type="text" name="drugName" ng-model="drug.name" required>
<span ng-show="myForm.drugName.$error" class="help-inline">
Required</span>
</div>
<a href="#/" class="btn">Cancel</a>
<button ng-click="save()" ng-disabled="isClean() || myForm.$invalid"
class="btn btn-primary">Save</button>
<button ng-click="destroy()" ng-show="project._id"
class="btn btn-danger">Delete</button>
</form>
My app.js CreateCtrl, I set RestangularProvider.setBaseUrl('/rest/v1');
:
function CreateCtrl($scope, $location, Restangular) {
$scope.save = function() {
Restangular.all('drugs/').post($scope.drug).then(function(project) {
$location.path('/list');
});
}
}
In my Go code, I am using gorilla, and here are the pertinent parts:
http.Handle("/rest/v1/drugs/", drugs.MakeMuxer("/rest/v1/drugs/"));
func MakeMuxer(prefix string) http.Handler {
log.Println("**** drugs.MakeMuxer(): " + prefix);
var m *mux.Router
// Pass through the prefix if we have one.
if prefix == "" {
m = mux.NewRouter()
} else {
m = mux.NewRouter().PathPrefix(prefix).Subrouter()
}
m.HandleFunc("/", CreateDrug).Methods("POST")
// Everything else should 404.
//m.HandleFunc("/{path:.*}", gorca.NotFoundFunc)
return m
}
func CreateDrug(w http.ResponseWriter, r *http.Request) {
log.Println("**** CreateDrug.... ");
log.Println("drugName: " + r.FormValue("drugName"))
//c := appengine.NewContext(r)
}
I can see that the POST is getting into "CreateDrug", but r.FormValue("drugName")
is empty (it is not empty when I use a browser rest plugin and set "drugName" to some value.
You need to call r.ParseForm()
before you can call r.FormValue
.
//edit
After looking up angularjs, I noticed it sends the data as json, so you have to use json.NewDecoder, example:
type Drug struct {
Name string `json:"drugName"`
}
func CreateDrug(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var d Drug
dec := json.NewDecoder(r.Body)
dec.Decode(&d)
log.Println("**** CreateDrug.... ")
log.Println("drugName:", d.Name)
}