chat-gpt生成的golang web框架

Golang 归档:202304
普通
浏览:409
2023-04-04 14:05:56
使用chat-gpt生成了一个最简单的,golang web框架,而且带正则路由。

我就直接上代码了:

main.go

package main

import (
    "fmt"
    "net/http"
    "regexp"
)

type Router struct {
    routes []*Route
}

type Route struct {
    pattern *regexp.Regexp
    handler http.HandlerFunc
}

func (r *Router) HandleFunc(pattern string, handler http.HandlerFunc) {
    route := &Route{
        pattern: regexp.MustCompile(pattern),
        handler: handler,
    }
    r.routes = append(r.routes, route)
}

func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    for _, route := range r.routes {
        if route.pattern.MatchString(req.URL.Path) {
            route.handler(w, req)
            return
        }
    }
    http.NotFound(w, req)
}

func main() {
    router := &Router{}

    router.HandleFunc("^/$", func(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, "Hello, world!")
    })

    router.HandleFunc("^/users/([0-9]+)$", func(w http.ResponseWriter, req *http.Request) {
        matches := router.routes[1].pattern.FindStringSubmatch(req.URL.Path)
        fmt.Fprintf(w, "User ID: %s", matches[1])
    })

    http.ListenAndServe(":8080", router)
}

运行:

go run .
注意事项
  • 此文章对你有帮助,对作者表示感谢(微信):
  • 本文地址:https://22v.net/article/3267/
  • 转载本文时,请注明转载自“SamBlog”的字样。
  • 如此文章有损您的合法权益,请使用页面底部的邮箱与我取得联系。
分类目录
文章归档
友情站点