drpkcwwav20524605 2016-10-16 12:19
浏览 110
已采纳

如何在golang中建立自己的简单路由器?

I am building own router in golang to understand logic , however I am getting 404 error not found normally, i able to running to server but I wrote function in hello name, it is not running. what could reason for this ?

package main
import (
    "fmt"
    "log"
    "net/http"
    "strings"
    "time"
)

var Session *http.Server
var r Router

func Run(port string) {
    Session = &http.Server{
        Addr:           port,
        Handler:        &r,
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }
    log.Fatal(Session.ListenAndServe())
}

type Handle func(http.ResponseWriter, *http.Request)

type Router struct {
    mux map[string]Handle
}

func newRouter() *Router {
    return &Router{
        mux: make(map[string]Handle),
    }
}

func (r *Router) Add(path string, handle Handle) {
    r.mux[path] = handle
}

func GetHeader(url string) string {
    sl := strings.Split(url, "/")
    return fmt.Sprintf("/%s", sl[1])
}

func (rt *Router) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    head := GetHeader(r.URL.Path)
    h, ok := rt.mux[head]
    if ok {
        h(w, r)
        return
    }
    http.NotFound(w, r)
}

func hello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "%s", "hello world")
}

func main() {
    r := newRouter()
    r.Add("/hello", hello)
    Run(":8080")
}
  • 写回答

2条回答 默认 最新

  • duanbu4962 2016-10-16 14:23
    关注

    Your main function, by using the := notation, is declaring and initialising a new local variable called r, whose scope is different from the global variable you have on the top of your listing.

    This means that the r variable that you're adding the handler to, is not the global one that you're trying to assign to the Http.Server struct, therefore your ServeHTTP will not find any mapping at all into its own receiver r.

    A solution is to declare the r Router as a pointer to a Router, like this:

    var r *Router
    

    and in your handler, you can pass directly the pointer without any dereference:

    Session = &http.Server{
            Addr:           port,
            Handler:        r,
            ReadTimeout:    10 * time.Second,
            WriteTimeout:   10 * time.Second,
            MaxHeaderBytes: 1 << 20,
        }
    

    Of course, remember to initialise the variable by assigning the pointer value and not declaring a new local one:

    func main() {
        r = newRouter()
        r.Add("/hello", hello)
        Run(":8080")
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?
  • ¥15 cgictest.cgi文件无法访问