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

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

Custom Server to handle request with specific path

问题

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

这是我编写的代码片段:

package main

import (
    "net/http"
    "fmt"
    "io"
    "time"
)


func myHandler(w http.ResponseWriter, req *http.Request){
    io.WriteString(w, "hello, world!\n")
}


func main() {

    // 自定义 HTTP 服务器
    s := &http.Server{
        Addr:           ":8080",
        Handler:        http.HandlerFunc(myHandler),
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }

    err := s.ListenAndServe()
    if err != nil {
        fmt.Printf("服务器启动失败: ", err.Error())
    }
}

受这个帖子的启发。

我的处理程序接受所有请求,例如 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.

package main

import (
        &quot;net/http&quot;
        &quot;fmt&quot;
        &quot;io&quot;
        &quot;time&quot;
    )


func myHandler(w http.ResponseWriter, req *http.Request){
    io.WriteString(w, &quot;hello, world!\n&quot;)
}


func main() {

    //Custom http server
    s := &amp;http.Server{
        Addr:           &quot;:8080&quot;,
        Handler:        http.HandlerFunc(myHandler),
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 &lt;&lt; 20,
    }

    err := s.ListenAndServe()
    if err != nil {
        fmt.Printf(&quot;Server failed: &quot;, err.Error())
    }
}

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库编写的。

func myHandler(w http.ResponseWriter, req *http.Request){
    io.WriteString(w, "hello, world!\n")
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/todo/something", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Response"))
    })

    s := &http.Server{
        Addr:           ":8080",
        Handler:        mux,
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }
    s.ListenAndServe()
}
英文:

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 -->

func myHandler(w http.ResponseWriter, req *http.Request){
    io.WriteString(w, &quot;hello, world!\n&quot;)
}

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc(&quot;/todo/something&quot;, func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte(&quot;Response&quot;))
    })

    s := &amp;http.Server{
        Addr:           &quot;:8080&quot;,
        Handler:        mux,
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 &lt;&lt; 20,
    }
    s.ListenAndServe()
}

答案2

得分: 0

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

func myHandler(w http.ResponseWriter, r *http.Request){
    io.WriteString(w, "hello, world!\n")
}

func main(){
    // 你可以注册多个处理器,只要它实现了http.Handler接口

    http.HandleFunc("/todo/something", myHandler)
    http.HandleFunc("/todo/thingTwo", func(w http.ResponseWriter, r *http.Request){

        something := strings.TrimPrefix(r.URL.Path, "/todo/")
        fmt.Fprintf(w, "We received %s", something)
    })

    http.ListenAndServe(":5000", nil) //将使用默认的ServerMux替代nil
}

这里的思路是,你可以在测试时使用默认的服务器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.

 func myHandler(w http.ResponseWriter, r *http.Request){
     io.WriteString(w, &quot;hello, world!\n&quot;)
 }

 func main(){
     // you can register multiple handlers 
     // as long as it implements the http.Handler interface

     http.HandleFunc(&quot;/todo/something&quot;, myHandler)
     http.HandleFunc(&quot;/todo/thingTwo&quot;, func(w http.ResponseWriter, r *http.Request){

         something := strings.TrimPrefix(r.URL.Path, &quot;/todo/&quot;)
         fmt.Fprintf(w, &quot;We received %s&quot;, something)
     })

     http.ListenAndServe(&quot;:5000&quot;, nil) //Will use the default ServerMux in place of nil
 }

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:

确定