Golang rest api and curl











up vote
-1
down vote

favorite












I would like to test my golang rest api using curl.



Command I used to do it:



curl -X POST -H "Content-Type: application/json" -d '{"username":"username","password":"password"}' "http://localhost:8000/api/rooms/signin"


simplified version of server I have written



package main

import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)

func main() {
fmt.Println("Listening on port 8000")

router := mux.NewRouter()
router.HandleFunc("/api/rooms/signin", Signin)

log.Fatal(http.ListenAndServe(":8000", router))
}

func Signin(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
fmt.Println("POST")
if err := r.ParseForm(); err != nil {
fmt.Println("parsing failed")
return
}
fmt.Println("parsing success")
fmt.Println(r.Form)
fmt.Println("path: ", r.URL.Path)
fmt.Println("scheme: ", r.URL.Scheme)
username := r.FormValue("username")
password := r.FormValue("password")
fmt.Println(username)
fmt.Println(password)

fmt.Println("username:", r.Form["username"])
fmt.Println("password:", r.Form["password"])

return
}
}


The problem is I get an empty form - this is the output I get



Listening on port 8000
POST
parsing success
map
path: /api/rooms/signin
scheme:


username:
password:


I suppose this is not right, but I can't think of anything I may be doing wrong. The expected output is to have "password" and "username" strings as the output of golang server.










share|improve this question


















  • 5




    You're not sending a form. You are sending JSON.
    – Peter
    Nov 9 at 15:49










  • thank you so much!
    – asdfgh
    Nov 9 at 15:55

















up vote
-1
down vote

favorite












I would like to test my golang rest api using curl.



Command I used to do it:



curl -X POST -H "Content-Type: application/json" -d '{"username":"username","password":"password"}' "http://localhost:8000/api/rooms/signin"


simplified version of server I have written



package main

import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)

func main() {
fmt.Println("Listening on port 8000")

router := mux.NewRouter()
router.HandleFunc("/api/rooms/signin", Signin)

log.Fatal(http.ListenAndServe(":8000", router))
}

func Signin(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
fmt.Println("POST")
if err := r.ParseForm(); err != nil {
fmt.Println("parsing failed")
return
}
fmt.Println("parsing success")
fmt.Println(r.Form)
fmt.Println("path: ", r.URL.Path)
fmt.Println("scheme: ", r.URL.Scheme)
username := r.FormValue("username")
password := r.FormValue("password")
fmt.Println(username)
fmt.Println(password)

fmt.Println("username:", r.Form["username"])
fmt.Println("password:", r.Form["password"])

return
}
}


The problem is I get an empty form - this is the output I get



Listening on port 8000
POST
parsing success
map
path: /api/rooms/signin
scheme:


username:
password:


I suppose this is not right, but I can't think of anything I may be doing wrong. The expected output is to have "password" and "username" strings as the output of golang server.










share|improve this question


















  • 5




    You're not sending a form. You are sending JSON.
    – Peter
    Nov 9 at 15:49










  • thank you so much!
    – asdfgh
    Nov 9 at 15:55















up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











I would like to test my golang rest api using curl.



Command I used to do it:



curl -X POST -H "Content-Type: application/json" -d '{"username":"username","password":"password"}' "http://localhost:8000/api/rooms/signin"


simplified version of server I have written



package main

import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)

func main() {
fmt.Println("Listening on port 8000")

router := mux.NewRouter()
router.HandleFunc("/api/rooms/signin", Signin)

log.Fatal(http.ListenAndServe(":8000", router))
}

func Signin(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
fmt.Println("POST")
if err := r.ParseForm(); err != nil {
fmt.Println("parsing failed")
return
}
fmt.Println("parsing success")
fmt.Println(r.Form)
fmt.Println("path: ", r.URL.Path)
fmt.Println("scheme: ", r.URL.Scheme)
username := r.FormValue("username")
password := r.FormValue("password")
fmt.Println(username)
fmt.Println(password)

fmt.Println("username:", r.Form["username"])
fmt.Println("password:", r.Form["password"])

return
}
}


The problem is I get an empty form - this is the output I get



Listening on port 8000
POST
parsing success
map
path: /api/rooms/signin
scheme:


username:
password:


I suppose this is not right, but I can't think of anything I may be doing wrong. The expected output is to have "password" and "username" strings as the output of golang server.










share|improve this question













I would like to test my golang rest api using curl.



Command I used to do it:



curl -X POST -H "Content-Type: application/json" -d '{"username":"username","password":"password"}' "http://localhost:8000/api/rooms/signin"


simplified version of server I have written



package main

import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
)

func main() {
fmt.Println("Listening on port 8000")

router := mux.NewRouter()
router.HandleFunc("/api/rooms/signin", Signin)

log.Fatal(http.ListenAndServe(":8000", router))
}

func Signin(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
fmt.Println("POST")
if err := r.ParseForm(); err != nil {
fmt.Println("parsing failed")
return
}
fmt.Println("parsing success")
fmt.Println(r.Form)
fmt.Println("path: ", r.URL.Path)
fmt.Println("scheme: ", r.URL.Scheme)
username := r.FormValue("username")
password := r.FormValue("password")
fmt.Println(username)
fmt.Println(password)

fmt.Println("username:", r.Form["username"])
fmt.Println("password:", r.Form["password"])

return
}
}


The problem is I get an empty form - this is the output I get



Listening on port 8000
POST
parsing success
map
path: /api/rooms/signin
scheme:


username:
password:


I suppose this is not right, but I can't think of anything I may be doing wrong. The expected output is to have "password" and "username" strings as the output of golang server.







linux go curl






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 9 at 15:42









asdfgh

4642820




4642820








  • 5




    You're not sending a form. You are sending JSON.
    – Peter
    Nov 9 at 15:49










  • thank you so much!
    – asdfgh
    Nov 9 at 15:55
















  • 5




    You're not sending a form. You are sending JSON.
    – Peter
    Nov 9 at 15:49










  • thank you so much!
    – asdfgh
    Nov 9 at 15:55










5




5




You're not sending a form. You are sending JSON.
– Peter
Nov 9 at 15:49




You're not sending a form. You are sending JSON.
– Peter
Nov 9 at 15:49












thank you so much!
– asdfgh
Nov 9 at 15:55






thank you so much!
– asdfgh
Nov 9 at 15:55














1 Answer
1






active

oldest

votes

















up vote
2
down vote



accepted










As pointed out in the comments, you are accepting a JSON payload and not a POST form. Here is a small snippet to aid you in handling JSON although there are a lot in the internet.



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

body, err := ioutil.ReadAll(r.Body)
if err != nil {
// error handling
}

params := make(map[string]string)
err = json.Unmarshal(body, &params)
if err != nil {
// error handling
}

fmt.Println("username:", params["username"])
fmt.Println("password:", params["password"])

}


I recommend creating a concrete struct rather than a map[string]string e.g.



type SigninBody struct {
Username string `json:"username"`
Password string `json:"password"`
}


And then passing it to json.Unmarshal like so:



var signinBody SinginBody
err = json.Unmarshal(body, &signinBody)


Here is a quick Playgroud






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53228898%2fgolang-rest-api-and-curl%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    2
    down vote



    accepted










    As pointed out in the comments, you are accepting a JSON payload and not a POST form. Here is a small snippet to aid you in handling JSON although there are a lot in the internet.



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

    body, err := ioutil.ReadAll(r.Body)
    if err != nil {
    // error handling
    }

    params := make(map[string]string)
    err = json.Unmarshal(body, &params)
    if err != nil {
    // error handling
    }

    fmt.Println("username:", params["username"])
    fmt.Println("password:", params["password"])

    }


    I recommend creating a concrete struct rather than a map[string]string e.g.



    type SigninBody struct {
    Username string `json:"username"`
    Password string `json:"password"`
    }


    And then passing it to json.Unmarshal like so:



    var signinBody SinginBody
    err = json.Unmarshal(body, &signinBody)


    Here is a quick Playgroud






    share|improve this answer

























      up vote
      2
      down vote



      accepted










      As pointed out in the comments, you are accepting a JSON payload and not a POST form. Here is a small snippet to aid you in handling JSON although there are a lot in the internet.



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

      body, err := ioutil.ReadAll(r.Body)
      if err != nil {
      // error handling
      }

      params := make(map[string]string)
      err = json.Unmarshal(body, &params)
      if err != nil {
      // error handling
      }

      fmt.Println("username:", params["username"])
      fmt.Println("password:", params["password"])

      }


      I recommend creating a concrete struct rather than a map[string]string e.g.



      type SigninBody struct {
      Username string `json:"username"`
      Password string `json:"password"`
      }


      And then passing it to json.Unmarshal like so:



      var signinBody SinginBody
      err = json.Unmarshal(body, &signinBody)


      Here is a quick Playgroud






      share|improve this answer























        up vote
        2
        down vote



        accepted







        up vote
        2
        down vote



        accepted






        As pointed out in the comments, you are accepting a JSON payload and not a POST form. Here is a small snippet to aid you in handling JSON although there are a lot in the internet.



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

        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
        // error handling
        }

        params := make(map[string]string)
        err = json.Unmarshal(body, &params)
        if err != nil {
        // error handling
        }

        fmt.Println("username:", params["username"])
        fmt.Println("password:", params["password"])

        }


        I recommend creating a concrete struct rather than a map[string]string e.g.



        type SigninBody struct {
        Username string `json:"username"`
        Password string `json:"password"`
        }


        And then passing it to json.Unmarshal like so:



        var signinBody SinginBody
        err = json.Unmarshal(body, &signinBody)


        Here is a quick Playgroud






        share|improve this answer












        As pointed out in the comments, you are accepting a JSON payload and not a POST form. Here is a small snippet to aid you in handling JSON although there are a lot in the internet.



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

        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
        // error handling
        }

        params := make(map[string]string)
        err = json.Unmarshal(body, &params)
        if err != nil {
        // error handling
        }

        fmt.Println("username:", params["username"])
        fmt.Println("password:", params["password"])

        }


        I recommend creating a concrete struct rather than a map[string]string e.g.



        type SigninBody struct {
        Username string `json:"username"`
        Password string `json:"password"`
        }


        And then passing it to json.Unmarshal like so:



        var signinBody SinginBody
        err = json.Unmarshal(body, &signinBody)


        Here is a quick Playgroud







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 9 at 16:07









        ssemilla

        3,032424




        3,032424






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53228898%2fgolang-rest-api-and-curl%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud

            Zucchini