dtgr6303 2018-11-09 15:42
浏览 42
已采纳

Golang Rest API和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.

  • 写回答

1条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 写c++代码,第7题说一下使用的计算方法
      • ¥15 postman接口自动化测试报告实践总结
      • ¥15 有关c++的问题,利用相关知识
      • ¥15 求香农编码和解码的matlab代码
      • ¥20 ROS中的TEB局部规划问题
      • ¥20 关于#matlab#的问题:要求测出上面图片中所有同心圆的半径
      • ¥20 epanet软件运行问题
      • ¥15 Python 文件读取
      • ¥60 dpabi进行Alff计算时脑池有干扰信号
      • ¥15 利用kmeans或kshape聚类分析对归一化的无量纲时间-降雨序列进行聚类