自定义服务器以处理特定路径的请求

huangapple go评论103阅读模式
英文:

Custom Server to handle request with specific path

问题

我想创建一个处理具有以下路径的请求的 API:http:\\localhost:8080\todo\something,但我需要使用自定义服务器来实现。

这是我编写的代码片段:

  1. package main
  2. import (
  3. "net/http"
  4. "fmt"
  5. "io"
  6. "time"
  7. )
  8. func myHandler(w http.ResponseWriter, req *http.Request){
  9. io.WriteString(w, "hello, world!\n")
  10. }
  11. func main() {
  12. // 自定义 HTTP 服务器
  13. s := &http.Server{
  14. Addr: ":8080",
  15. Handler: http.HandlerFunc(myHandler),
  16. ReadTimeout: 10 * time.Second,
  17. WriteTimeout: 10 * time.Second,
  18. MaxHeaderBytes: 1 << 20,
  19. }
  20. err := s.ListenAndServe()
  21. if err != nil {
  22. fmt.Printf("服务器启动失败: ", err.Error())
  23. }
  24. }

受这个帖子的启发。

我的处理程序接受所有请求,例如 http:localhost:8080\abchttp:localhost:8080\abc 等。如何在自定义服务器中指定路径,以便只处理与该路径匹配的请求?

英文:

I want to make a api which handles the request which have the path such as
http:\\localhost:8080\todo\something but I need to do using custom server.

Here is the piece of code I have written.

  1. package main
  2. import (
  3. &quot;net/http&quot;
  4. &quot;fmt&quot;
  5. &quot;io&quot;
  6. &quot;time&quot;
  7. )
  8. func myHandler(w http.ResponseWriter, req *http.Request){
  9. io.WriteString(w, &quot;hello, world!\n&quot;)
  10. }
  11. func main() {
  12. //Custom http server
  13. s := &amp;http.Server{
  14. Addr: &quot;:8080&quot;,
  15. Handler: http.HandlerFunc(myHandler),
  16. ReadTimeout: 10 * time.Second,
  17. WriteTimeout: 10 * time.Second,
  18. MaxHeaderBytes: 1 &lt;&lt; 20,
  19. }
  20. err := s.ListenAndServe()
  21. if err != nil {
  22. fmt.Printf(&quot;Server failed: &quot;, err.Error())
  23. }
  24. }

inspired by this post

My handler accepts all the request such http:localhost:8080\abc, http:localhost:8080\abc etc
How to give path in custom server so that it handles request only that matches the path.

答案1

得分: 3

如果你想使用不同的URL路径,你需要创建一些mux,你可以创建一个,使用Go提供的默认mux,或者使用像gorilla这样的第三方mux。

以下代码是使用标准的http库编写的。

  1. func myHandler(w http.ResponseWriter, req *http.Request){
  2. io.WriteString(w, "hello, world!\n")
  3. }
  4. func main() {
  5. mux := http.NewServeMux()
  6. mux.HandleFunc("/todo/something", func(w http.ResponseWriter, r *http.Request) {
  7. w.Write([]byte("Response"))
  8. })
  9. s := &http.Server{
  10. Addr: ":8080",
  11. Handler: mux,
  12. ReadTimeout: 10 * time.Second,
  13. WriteTimeout: 10 * time.Second,
  14. MaxHeaderBytes: 1 << 20,
  15. }
  16. s.ListenAndServe()
  17. }
英文:

If you want to use different URL paths, you have to create some mux, you can create one, use the default mux provided by go or use a third party mux like gorilla.

The following code is made using the standart http library provided.

<!-- language: go -->

  1. func myHandler(w http.ResponseWriter, req *http.Request){
  2. io.WriteString(w, &quot;hello, world!\n&quot;)
  3. }
  4. func main() {
  5. mux := http.NewServeMux()
  6. mux.HandleFunc(&quot;/todo/something&quot;, func(w http.ResponseWriter, r *http.Request) {
  7. w.Write([]byte(&quot;Response&quot;))
  8. })
  9. s := &amp;http.Server{
  10. Addr: &quot;:8080&quot;,
  11. Handler: mux,
  12. ReadTimeout: 10 * time.Second,
  13. WriteTimeout: 10 * time.Second,
  14. MaxHeaderBytes: 1 &lt;&lt; 20,
  15. }
  16. s.ListenAndServe()
  17. }

答案2

得分: 0

只是补充一下,虽然不推荐,但一个好的起点是尝试使用标准库中的DefaultServeMux进行实验。当你没有提供mux给http服务器时,会使用DefaultServeMux。

  1. func myHandler(w http.ResponseWriter, r *http.Request){
  2. io.WriteString(w, "hello, world!\n")
  3. }
  4. func main(){
  5. // 你可以注册多个处理器,只要它实现了http.Handler接口
  6. http.HandleFunc("/todo/something", myHandler)
  7. http.HandleFunc("/todo/thingTwo", func(w http.ResponseWriter, r *http.Request){
  8. something := strings.TrimPrefix(r.URL.Path, "/todo/")
  9. fmt.Fprintf(w, "We received %s", something)
  10. })
  11. http.ListenAndServe(":5000", nil) //将使用默认的ServerMux替代nil
  12. }

这里的思路是,你可以在测试时使用默认的服务器Mux,像@Motakjuq展示的那样创建自己的Mux并分配给你的服务器,或者你可以使用第三方的路由库,比如go-chihttprouter,或者从这里的一个不错的集合中挑选一个here,或者简单地查看stdlib

英文:

Just to add on, though not recommended but a good starting point is to experiment with the DefaultServeMux that also comes with the std lib. The DefaultServeMux is used when you don't supply a mux to the http server.

  1. func myHandler(w http.ResponseWriter, r *http.Request){
  2. io.WriteString(w, &quot;hello, world!\n&quot;)
  3. }
  4. func main(){
  5. // you can register multiple handlers
  6. // as long as it implements the http.Handler interface
  7. http.HandleFunc(&quot;/todo/something&quot;, myHandler)
  8. http.HandleFunc(&quot;/todo/thingTwo&quot;, func(w http.ResponseWriter, r *http.Request){
  9. something := strings.TrimPrefix(r.URL.Path, &quot;/todo/&quot;)
  10. fmt.Fprintf(w, &quot;We received %s&quot;, something)
  11. })
  12. http.ListenAndServe(&quot;:5000&quot;, nil) //Will use the default ServerMux in place of nil
  13. }

The idea here is that you can use the default server Mux for testing, create your own Mux like @Motakjuq showed you using the http.NewServeMux() and assign to your server or you can use a thirdparty router lib like go-chi, httprouter or simply take your pick from a nice collection here or simply review the stdlib

huangapple
  • 本文由 发表于 2017年1月22日 10:19:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/41786677.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定