dsp1836 2015-10-21 08:37
浏览 13
已采纳

如何通过邮递员在Go lang中处理GET操作(CRUD)?

I want to perform a get operation. I am passng name as a resource to the URL. The URL I am hitting in Postman is : localhost:8080/location/{titan rolex} ( I chose the GET method in the dropdown list) On the URL hit in Postman, I am executing the GetUser func() with body as:

func GetUser(rw http.ResponseWriter, req *http.Request) {

}

Now I wish to get the resource value i.e 'titan rolex' in the GetUser method. How can I achieve this in golang?

In main(), I have this :

http.HandleFunc("/location/{titan rolex}", GetUser)

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • doutan2111 2015-10-21 09:06
    关注

    What you are doing is binding the complete path /location/{titan rolex} to be handled by GetUser.

    What you really want is to bind /location/<every possible string> to be handled by one handler (e.g. LocationHandler).

    You can do that with either the standard library or another router. I will present both ways:

    1. Standard lib:

      import (
          "fmt"
          "net/http"
          "log"
      )
      
      func locationHandler(w http.ResponseWriter, r *http.Request) {
          name := r.URL.Path[len("/location/"):]
          fmt.Fprintf(w, "Location: %s
      ", name)
      }
      
      func main() {
          http.HandleFunc("/location/", locationHandler)
          log.Fatal(http.ListenAndServe(":8080", nil))
      }
      

      Note however, more complex paths (such as /location/<every possible string>/<some int>/<another string>) will be tedious to implement this way.

    2. The other way is to use github.com/julienschmidt/httprouter, especially if you encounter these situations more often (and have more complex paths).

      Here's an example for your use case:

      import (
          "fmt"
          "github.com/julienschmidt/httprouter"
          "net/http"
          "log"
      )
      
      func LocationHandler(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
          fmt.Fprintf(w, "Location: %s
      ", ps.ByName("loc"))
      }
      
      func main() {
          router := httprouter.New()
          router.GET("/location/:loc", LocationHandler)
      
          log.Fatal(http.ListenAndServe(":8080", router))
      }
      

      Note that httprouter uses a slightly different signature for handlers. This is because, as you can see, it passes these parameters to the functions as well.

    Oh and another note, you can just hit http://localhost:8080/location/titan rolex with your browser (or something else) - if that something else is decent enough, it will URLEncode that to be http://localhost:8080/location/titan%20rolex.

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

报告相同问题?

悬赏问题

  • ¥20 蓝牙耳机怎么查看日志
  • ¥15 R语言 拟时序分析降维图如何减少分支
  • ¥15 Fluent齿轮搅油
  • ¥15 八爪鱼爬数据为什么自己停了
  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统