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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?