2014-07-06 01:15
浏览 45

在Go中无法获取Angular / Restangular表单数据

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">
<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>

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) {

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.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duangai1368
    duangai1368 2014-07-06 01:55

    You need to call r.ParseForm() before you can call r.FormValue.


    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)
        log.Println("**** CreateDrug.... ")
        log.Println("drugName:", d.Name)
    点赞 评论