惊风破浪的博客
PHP
MySQL
Redis
Linux
算法与设计模式
杂项
Golang
登录
goweb开发(一)
2周前 ⋅
0
###### `定义web服务器` ```go package main import ( "fmt" "net/http" ) func handlerFunc(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "<h1>Hello, 这里是 goblog</h1>") } func main() { http.HandleFunc("/", handlerFunc) http.ListenAndServe(":3000", nil) } ``` - 安装air自动重载功能; - go env -w GOPROXY=https://goproxy.cn - go get -u github.com/cosmtrek/air - air -v - 配置 - 设置标头 w.Header().Set("Content-Type", "text/html; charset=utf-8") - 设置状态 w.WriteHeader(http.StatusNotFound) - 路径 r.URL.Path - 如何设置输出 fmt.Fprint(标准i/o库) ###### `配置路由` 方式 - ServeMux - Handler ServeMux :多路复用路由,简单高效,不支持过滤,不支持URL参数,不支持路由命名; ServeMux创建方式 ```go router := http.NewServeMux() // 文章详情 router.HandleFunc("/articles/", func(w http.ResponseWriter, r *http.Request) { id := strings.SplitN(r.URL.Path, "/", 3)[2] fmt.Fprint(w, "文章 ID:"+id) }) http.ListenAndServe(":3000", router) ``` ###### `集成 Gorilla Mux` 如何安装: go get -u github.com/gorilla/mux - 如何定义路由 ```go router := mux.NewRouter() router.HandleFunc("/", homeHandler).Methods("GET").Name("home") router.HandleFunc("/about", aboutHandler).Methods("GET").Name("about") // 通过命名路由获取 URL 示例 homeURL, _ := router.Get("home").URL() fmt.Println("homeURL: ", homeURL) http.ListenAndServe(":3000", router) ``` - 自定义中间件 ``` router.Use(forceHTMLMiddleware) ``` ```自定义404 router.NotFoundHandler = http.HandlerFunc(notFoundHandler) ```
回复
发布文章
友情链接
Mr.Zhu
Swoole
PHP官网
菜鸟教程
Go语言中文网
implode
数据结构与算法