phantom_wizard
phantom_wizard

Reputation: 3178

Golang rest api and curl

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.

Upvotes: 0

Views: 2439

Answers (1)

ssemilla
ssemilla

Reputation: 3968

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

Upvotes: 4

Related Questions