FAQ
Hello all, I've been working quite a while with GOLang, but i thought there
are something i'm doing well. The following source has an API '/api/user'
that accepts POST / OPTIONS/GET method, but the problem is that it doesn't
grab the JSON data that sent via AngularJS Ajax Request, but if i use CURL
it would grabbed it with problem or any error.

GO Sources:

package main

import (
     _"fmt"
     "net/http"
     "encoding/json"
     "github.com/gorilla/mux"
     "log"
     "io/ioutil"
)

type UserInfo struct{
     FirstName string "json:firstname"
     LastName string "json:lastname"
     MiddleName string "json:middlename"
}

type AllUsers struct{
     Users []UserInfo
}

type Error struct{
     Message string
}

type Route struct{
     Name string
     Method string
     Pattern string
     HandlerFunc http.HandlerFunc
}

type Routes []Route

var routes = Routes{
     Route{
       "Index",
       "GET",
       "/",
       Index,
     },
     Route{
         "User",
         "POST",
         "/api/user",
         User,
     },
}

func Index(w http.ResponseWriter, r *http.Request){

}

func User(w http.ResponseWriter, r *http.Request){
     w.Header().Set("Content-Type", "application/json")
     w.Header().Set("Access-Control-Allow-Headers", "Origin,
X-Requested-With, Content-Type, Accept, Authorization")
     w.Header().Set("Access-Control-Allow-Origin", "*")

       body, err := ioutil.ReadAll(r.Body)
       log.Println(body)
       if err != nil{
         log.Println(err)
         panic(w,r)
         return
       }
       log.Println(string(body))
       var user UserInfo
       err = json.Unmarshal(body, &user)
       if err != nil{
         log.Println(err)
         panic(w,r)
         return
       }
       log.Println(user.FirstName)
     /**
       decoder := json.NewDecoder(r.Body)
       var user_info UserInfo
       err := decoder.Decode(&user_info)
         if(err != nil){
             panic(w, r)
             log.Println(err)
             return
         }
       fmt.Println(user_info.FirstName)
     **/

       w.Write([]byte("Hello"));
}

func panic(w http.ResponseWriter, r * http.Request){
   w.Header().Set("Content-Type", "application/json")
   w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With,
Content-Type, Accept, Authorization")
   w.Header().Set("Access-Control-Allow-Origin", "*")

   ErrorSlice := Error {
     Message : "Invalid JSON Request",
   }

   output,_ := json.Marshal(ErrorSlice)
   log.Println(string(output))

   w.Write([]byte(output))
}

func APIDescribe(w http.ResponseWriter, r *http.Request){
   w.Header().Set("Content-Type", "application/json")
   w.Header().Set("Access-Control-Allow-Headers", "Origin, X-Requested-With,
Content-Type, Accept, Authorization")
   w.Header().Set("Access-Control-Allow-Origin", "*")
}

func main(){
     routes := mux.NewRouter()
     routes.HandleFunc("/api/user", User).Methods("POST","GET", "OPTIONS")
     http.Handle("/", routes)
     http.ListenAndServe(":8080", nil)
}


--------------------------------
Angular JS Source Code:
----------------------------------

$scope.JSONData = {
           FirstName: "Emmanuel",
           LastName : "Osinnowo",
           MiddleName: "Itunu"
}

$http({
      method: "GET",
      data: $scope.JSONData,
      url: "http://localhost:8080/api/user",
      headers: {
          'Content-Type': 'application/json',
      }
}).success(function(data){
deffered.resolve(data);
}).error(function(error){
deffered.resolve(error)
});

--------------------------------------------------------------
Inside my console where i log any request , i realized that the body is
returning [ ]. Any Help please, I would be very grateful.

Thanks in advance.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Search Discussions

  • Matt Silverlock at Dec 1, 2015 at 1:06 pm
    The struct tags for the User type in your Go code don't match the case/format of the JSON keys in your Angular code.

    Go has firstname and Angular has FirstName.

    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/d/optout.
  • Piers at Dec 1, 2015 at 5:09 pm
    In fact the struct tags are wrong in more ways that that, you want
    `json:"field"` not "json:field". It's more robust sometimes to leave struct
    tags off completely for unmarshalling, then you'll get a case insensitive
    match against the incoming JSON keys.


    On Tuesday, 1 December 2015 13:06:21 UTC, Matt Silverlock wrote:

    The struct tags for the User type in your Go code don't match the
    case/format of the JSON keys in your Angular code.

    Go has firstname and Angular has FirstName.
    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/d/optout.
  • Paul Kölle at Dec 2, 2015 at 1:09 pm
    Am 01.12.2015 um 10:26 schrieb
    emmanuel.osinnowo@upperlink.ng:
    --------------------------------
    Angular JS Source Code:
    ----------------------------------

    $scope.JSONData = {
    FirstName: "Emmanuel",
    LastName : "Osinnowo",
    MiddleName: "Itunu"
    }

    $http({
    method: "GET",
    Maybe try POST here...

    cheers
       Paul


    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/d/optout.
  • Jimmi Prajapati at Dec 2, 2015 at 1:09 pm
    Please use these tools http://codebeautify.org/jsonviewer and
    http://jsonformatter.org for posting json data before copy here..

    Thanks.
    Jimmi

    On Tuesday, December 1, 2015 at 2:57:14 PM UTC+5:30,
    emmanuel...@upperlink.ng wrote:
    Hello all, I've been working quite a while with GOLang, but i thought
    there are something i'm doing well. The following source has an API
    '/api/user' that accepts POST / OPTIONS/GET method, but the problem is
    that it doesn't grab the JSON data that sent via AngularJS Ajax Request,
    but if i use CURL it would grabbed it with problem or any error.

    GO Sources:

    package main

    import (
    _"fmt"
    "net/http"
    "encoding/json"
    "github.com/gorilla/mux"
    "log"
    "io/ioutil"
    )

    type UserInfo struct{
    FirstName string "json:firstname"
    LastName string "json:lastname"
    MiddleName string "json:middlename"
    }

    type AllUsers struct{
    Users []UserInfo
    }

    type Error struct{
    Message string
    }

    type Route struct{
    Name string
    Method string
    Pattern string
    HandlerFunc http.HandlerFunc
    }

    type Routes []Route

    var routes = Routes{
    Route{
    "Index",
    "GET",
    "/",
    Index,
    },
    Route{
    "User",
    "POST",
    "/api/user",
    User,
    },
    }

    func Index(w http.ResponseWriter, r *http.Request){

    }

    func User(w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("Access-Control-Allow-Headers", "Origin,
    X-Requested-With, Content-Type, Accept, Authorization")
    w.Header().Set("Access-Control-Allow-Origin", "*")

    body, err := ioutil.ReadAll(r.Body)
    log.Println(body)
    if err != nil{
    log.Println(err)
    panic(w,r)
    return
    }
    log.Println(string(body))
    var user UserInfo
    err = json.Unmarshal(body, &user)
    if err != nil{
    log.Println(err)
    panic(w,r)
    return
    }
    log.Println(user.FirstName)
    /**
    decoder := json.NewDecoder(r.Body)
    var user_info UserInfo
    err := decoder.Decode(&user_info)
    if(err != nil){
    panic(w, r)
    log.Println(err)
    return
    }
    fmt.Println(user_info.FirstName)
    **/

    w.Write([]byte("Hello"));
    }

    func panic(w http.ResponseWriter, r * http.Request){
    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("Access-Control-Allow-Headers", "Origin,
    X-Requested-With, Content-Type, Accept, Authorization")
    w.Header().Set("Access-Control-Allow-Origin", "*")

    ErrorSlice := Error {
    Message : "Invalid JSON Request",
    }

    output,_ := json.Marshal(ErrorSlice)
    log.Println(string(output))

    w.Write([]byte(output))
    }

    func APIDescribe(w http.ResponseWriter, r *http.Request){
    w.Header().Set("Content-Type", "application/json")
    w.Header().Set("Access-Control-Allow-Headers", "Origin,
    X-Requested-With, Content-Type, Accept, Authorization")
    w.Header().Set("Access-Control-Allow-Origin", "*")
    }

    func main(){
    routes := mux.NewRouter()
    routes.HandleFunc("/api/user", User).Methods("POST","GET", "OPTIONS")
    http.Handle("/", routes)
    http.ListenAndServe(":8080", nil)
    }


    --------------------------------
    Angular JS Source Code:
    ----------------------------------

    $scope.JSONData = {
    FirstName: "Emmanuel",
    LastName : "Osinnowo",
    MiddleName: "Itunu"
    }

    $http({
    method: "GET",
    data: $scope.JSONData,
    url: "http://localhost:8080/api/user",
    headers: {
    'Content-Type': 'application/json',
    }
    }).success(function(data){
    deffered.resolve(data);
    }).error(function(error){
    deffered.resolve(error)
    });

    --------------------------------------------------------------
    Inside my console where i log any request , i realized that the body is
    returning [ ]. Any Help please, I would be very grateful.

    Thanks in advance.
    --
    You received this message because you are subscribed to the Google Groups "golang-nuts" group.
    To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
    For more options, visit https://groups.google.com/d/optout.

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
groupgolang-nuts @
categoriesgo
postedDec 1, '15 at 9:27a
activeDec 2, '15 at 1:09p
posts5
users5
websitegolang.org

People

Translate

site design / logo © 2021 Grokbase