如何使用Go解决POST 404错误?不是源代码错误

时间:2019-09-18 13:47:13

标签: go

我用golang书输入我的源代码。 我的源代码与golang书的源代码相同

检查源代码

------- golang --------

package main

import (
    "fmt"
    "net/http"
)

func main() {
   r := &router{make(map[string]map[string]HandlerFunc)}

   r.HandleFunc("GET", "/", func(c *Context) {
       fmt.Fprintln(c.ResponseWriter, "welcome!")
   })

   r.HandleFunc("GET", "/about", func(c *Context) {
       fmt.Fprintln(c.ResponseWriter, "about")
   })

   r.HandleFunc("GET", "/users/:id", func(c *Context) {
       fmt.Fprintf(c.ResponseWriter, "retrieve user %v\n",
       c.Params["id"])
   })

   r.HandleFunc("GET", "/users/:user_id/addresses/:address_id", func(c *Context) {
       fmt.Fprintf(c.ResponseWriter, "retrieve user %v's address %v\n",
       c.Params["user_id"], c.Params["address_id"])
   })

   r.HandleFunc("POST", "/users", func(c *Context) {
       fmt.Fprintf(c.ResponseWriter, "create user\n")
   })

   r.HandleFunc("POST", "/users/:user_id/addresses", func(c *Context) {
       fmt.Fprintf(c.ResponseWriter, "create user %v's address\n", c.Params["user_id"])
   })

   http.ListenAndServe(":8080", r)
}

PS C:\ Users \ user \ go> curl http://localhost:8080/users/1 curl:找不到404页 在第1行:char:1 +卷曲http://localhost:8080/users/1 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~     + CategoryInfo:InvalidOperation:(System.Net.HttpWebRequest:HttpWebRequest)[Invoke-WebRequest],WebException     + FullyQualifiedErrorId:WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

1 个答案:

答案 0 :(得分:-1)

在为HandlerFunc定义uri时,参数必须介于{}

之间

/ users / {id}代替/ users /:id