Junior — Middle
Can you explain how the router works in Go?
sobes.tech AI
Answer from AI
In the Go language, a router is typically used in the context of web frameworks to handle HTTP requests. Its task is to match incoming URLs and HTTP methods with the corresponding handler. The working principle is simple:
- The router stores a set of rules (routes), where each path and method corresponds to a handler function.
- When a request arrives, the router searches for a suitable route by URL and method.
- If a route is found, the associated handler is called, which generates a response.
Example of a simple router using the standard net/http package:
package main
import (
"fmt"
"net/http"
)
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello, world!")
}
func main() {
http.HandleFunc("/hello", helloHandler) // Register route
http.ListenAndServe(":8080", nil) // Start server
}
Here, http.HandleFunc acts as a simple router that links the path /hello to the helloHandler function. More complex routers (e.g., gorilla/mux) support path parameters, methods, middleware, etc.