英文:
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\abc
、http: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 (
"net/http"
"fmt"
"io"
"time"
)
func myHandler(w http.ResponseWriter, req *http.Request){
io.WriteString(w, "hello, world!\n")
}
func main() {
//Custom http server
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("Server failed: ", 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, "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()
}
答案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-chi、httprouter,或者从这里的一个不错的集合中挑选一个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, "hello, world!\n")
}
func main(){
// you can register multiple handlers
// as long as it implements the http.Handler interface
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) //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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论