golang轻量级高性能HTTP路由插件库alien的使用

Golang轻量级高性能HTTP路由插件库alien的使用

Alien是一个轻量级的Go语言HTTP路由器(多路复用器),专为不喜欢魔法的人们设计。它具有高性能、简洁的特点,且只依赖标准库。

主要特性

  • 快速性能(可查看基准测试)
  • 轻量级(仅一个文件)
  • 线程安全(设计考虑了并发)
  • 支持中间件
  • 支持路由分组
  • 无外部依赖(仅标准库)

安装

go get github.com/gernest/alien

使用示例

静态路由

package main

import (
	"log"
	"net/http"

	"github.com/gernest/alien"
)

func main() {
	m := alien.New()
	m.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello world"))
	})
	log.Fatal(http.ListenAndServe(":8090", m))
}

访问localhost:8090/将输出"hello world"

命名参数

package main

import (
	"log"
	"net/http"

	"github.com/gernest/alien"
)

func main() {
	m := alien.New()
	m.Get("/hello/:name", func(w http.ResponseWriter, r *http.Request) {
		p := alien.GetParams(r)
		w.Write([]byte(p.Get("name")))
	})
	log.Fatal(http.ListenAndServe(":8090", m))
}

访问/hello/tanzania将输出"tanzania"

通配参数

package main

import (
	"log"
	"net/http"

	"github.com/gernest/alien"
)

func main() {
	m := alien.New()
	m.Get("/hello/*name", func(w http.ResponseWriter, r *http.Request) {
		p := alien.GetParams(r)
		w.Write([]byte(p.Get("name")))
	})
	log.Fatal(http.ListenAndServe(":8090", m))
}

访问/hello/my/margicl/sheeplike/ship将输出"my/margical/sheeplike/ship"

中间件

中间件可以是任何满足func(http.Handler)http.Handler接口的函数。

package main

import (
	"log"
	"net/http"

	"github.com/gernest/alien"
)

func middleware(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("hello middlware"))
	})
}

func main() {
	m := alien.New()
	m.Use(middleware)
	m.Get("/", func(_ http.ResponseWriter, _ *http.Request) {
	})
	log.Fatal(http.ListenAndServe(":8090", m))
}

访问/将输出"hello middleware"

路由分组

package main

import (
	"log"
	"net/http"

	"github.com/gernest/alien"
)

func main() {
	m := alien.New()
	g := m.Group("/home")
	m.Use(middleware)
	g.Get("/alone", func(w http.ResponseWriter, _ *http.Request) {
		w.Write([]byte("home alone"))
	})
	log.Fatal(http.ListenAndServe(":8090", m))
}

访问/home/alone将输出"home alone"

作者

Geofrey Ernest (@gernesti)

许可证

MIT许可证


更多关于golang轻量级高性能HTTP路由插件库alien的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang轻量级高性能HTTP路由插件库alien的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


Alien - 轻量级高性能Golang HTTP路由库

Alien是一个轻量级但高性能的Golang HTTP路由库,它的设计目标是简单易用同时保持高性能。下面我将详细介绍Alien的使用方法和示例代码。

安装Alien

go get github.com/gernest/alien

基本使用

1. 创建路由实例

package main

import (
	"fmt"
	"net/http"
	
	"github.com/gernest/alien"
)

func main() {
	mux := alien.New()
	
	// 添加路由
	mux.Get("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, "Welcome to Alien!")
	})
	
	// 启动服务器
	http.ListenAndServe(":8080", mux)
}

2. 支持多种HTTP方法

mux.Post("/users", createUser)
mux.Put("/users/:id", updateUser)
mux.Delete("/users/:id", deleteUser)
mux.Patch("/users/:id", patchUser)
mux.Head("/users", listUsersHead)

3. 路径参数

mux.Get("/users/:id", func(w http.ResponseWriter, r *http.Request) {
	id := alien.GetParam(r, "id")
	fmt.Fprintf(w, "User ID: %s", id)
})

4. 通配符匹配

mux.Get("/files/*filepath", func(w http.ResponseWriter, r *http.Request) {
	filepath := alien.GetParam(r, "filepath")
	fmt.Fprintf(w, "Requested file: %s", filepath)
})

高级特性

1. 路由分组

api := mux.Group("/api")
api.Get("/users", listUsers)      // 匹配 /api/users
api.Post("/users", createUser)    // 匹配 /api/users

2. 中间件支持

func logger(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Printf("%s %s\n", r.Method, r.URL.Path)
		next.ServeHTTP(w, r)
	})
}

mux.Use(logger)  // 全局中间件

// 分组中间件
authGroup := mux.Group("/admin")
authGroup.Use(authMiddleware)

3. 静态文件服务

mux.ServeFiles("/static/*filepath", http.Dir("./public"))

完整示例

package main

import (
	"fmt"
	"log"
	"net/http"
	
	"github.com/gernest/alien"
)

func main() {
	mux := alien.New()
	
	// 全局中间件
	mux.Use(loggingMiddleware)
	
	// 首页
	mux.Get("/", homeHandler)
	
	// 用户路由组
	userGroup := mux.Group("/users")
	userGroup.Get("/", listUsersHandler)
	userGroup.Post("/", createUserHandler)
	userGroup.Get("/:id", getUserHandler)
	userGroup.Put("/:id", updateUserHandler)
	userGroup.Delete("/:id", deleteUserHandler)
	
	// 静态文件
	mux.ServeFiles("/static/*filepath", http.Dir("./static"))
	
	log.Println("Server started on :8080")
	log.Fatal(http.ListenAndServe(":8080", mux))
}

func loggingMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		log.Printf("%s %s", r.Method, r.URL.Path)
		next.ServeHTTP(w, r)
	})
}

func homeHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Welcome to the homepage!")
}

func listUsersHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "List of users")
}

func createUserHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Create user")
}

func getUserHandler(w http.ResponseWriter, r *http.Request) {
	id := alien.GetParam(r, "id")
	fmt.Fprintf(w, "Get user with ID: %s", id)
}

func updateUserHandler(w http.ResponseWriter, r *http.Request) {
	id := alien.GetParam(r, "id")
	fmt.Fprintf(w, "Update user with ID: %s", id)
}

func deleteUserHandler(w http.ResponseWriter, r *http.Request) {
	id := alien.GetParam(r, "id")
	fmt.Fprintf(w, "Delete user with ID: %s", id)
}

性能特点

  1. 轻量级:代码简洁,不依赖太多外部包
  2. 快速路由匹配:使用高效的匹配算法
  3. 低内存占用:设计上注重减少内存使用
  4. 零分配:在路由匹配过程中避免内存分配

与其他路由库对比

  • 比标准库http.ServeMux功能更丰富
  • gorilla/mux更轻量
  • httprouter更简单的API

Alien非常适合需要轻量级路由的中小型项目,它在性能和功能之间取得了很好的平衡。如果你的项目不需要复杂的功能,但需要高性能的路由,Alien是一个很好的选择。

希望这个介绍对你有帮助!如果需要更详细的信息,可以参考Alien的官方文档或源代码。

回到顶部