[go]自定义服务器处理具有特定路径的请求

时间:2017-01-22 02:19:53

标签: http go

我想创建一个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() {

    //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())
    }
}

受此post

的启发

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

2 个答案:

答案 0 :(得分:2)

如果你想使用不同的URL路径,你必须创建一些mux,你可以创建一个,使用go提供的默认多路复用器或使用第三方多路复用器,如gorilla

以下代码是使用提供的标准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()
}

答案 1 :(得分:0)

只需添加,尽管不建议这样做,但是一个不错的起点是尝试同时使用std库附带的DefaultServeMux。当您不向http服务器提供多路复用器时,将使用DefaultServeMux。

 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
 }

这里的想法是,您可以使用默认服务器Mux进行测试,使用@ .Motakjuq创建您自己的Mux,使用http.NewServeMux()向您展示,然后分配给您的服务器,也可以使用第三方路由器lib(例如{{ 3}},go-chi或只是从一个不错的收藏集httprouter中选择,或者只是查看here

相关问题