8000 GitHub - nicolasparada/go-mux: Golang HTTP request multiplexer
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
This repository was archived by the owner on Feb 15, 2024. It is now read-only.

nicolasparada/go-mux

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go Reference

Mux

A golang HTTP request multiplexer.

Install

go get github.com/nicolasparada/go-mux

Usage

Simple: familiar API using http.Handler and http.HandlerFunc interfaces.

func main() {
  r := mux.NewRouter()
  r.Handle("/test", test)

  http.ListenAndServe(":4000", r)
}

URL param: capture URL parameters with {myParam} notation, and access them with mux.URLParam(ctx, "myParam").

func main() {
  r := mux.NewRouter()
  r.HandleFunc("/hello/{name}", hello)

  http.ListenAndServe(":4000", r)
}

func hello(w http.ResponseWriter, r *http.Request) {
    name := mux.URLParam(r.Context(), "name")
    fmt.Fprintf(w, "Hello, %s", name)
}

Wildcard: match anything with *.

func main() {
  r := mux.NewRouter()
  r.Handle("/*", http.FileServer(http.FS(static)))

  http.ListenAndServe(":4000", r)
}

REST: mux by HTTP method using mux.MethodHandler. It will respond with 405 Method Not Allowed for you if none match.

func main() {
  r := mux.NewRouter()
  r.Handle("/api/todos", mux.MethodHandler{
    http.MethodPost: createTodo,
    http.MethodGet:  todos,
  })
  r.Handle("/api/todos/{todoID}", mux.MethodHandler{
    http.MethodGet:    todo,
    http.MethodPatch:  updateTodo,
    http.MethodDelete: deleteTodo,
  })

  http.ListenAndServe(":4000", r)
}

About

Golang HTTP request multiplexer

Topics

Resources

License

Stars

Watchers

Forks

Languages

0