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 Stata链式中介效应代码修改
  • ¥15 latex投稿显示click download
  • ¥15 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 添加组件无法加载页面,某块加载卡住
  • ¥15 网络科学导论,网络控制
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错