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条回答 默认 最新

  • dotws86260 2018-11-09 16:07
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)