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 数电设计题 没有设计思路 不知道用什么芯片进行设计 求提供设计思路
  • ¥15 在动态多目标优化问题中,第一幅图展示的是问题DF6的相关定义和绘制的POS和POF图,请问图中公式PS(t)和PF(t)是如何推导的
  • ¥60 设计一种优化算法结合案例给出智能仓储四向穿梭车的调度计划
  • ¥15 Errno2:No such file or directory,在当前文件确实没有该图片,怎么解决?
  • ¥15 博世摄像头数据存储的问题(iscsi)
  • ¥15 如何实现对学生籍贯信息管理系统的选择排序
  • ¥15 写一个51单片机的时钟代码
  • ¥15 git clone报错
  • ¥15 3d-slicer超声造影动态图像导入报错
  • ¥15 化工过程分析与合成问题求解决