Home  >  Article  >  Backend Development  >  Examples to explain how to use Golang to implement routing

Examples to explain how to use Golang to implement routing

PHPz
PHPzOriginal
2023-04-11 09:17:251554browse

Golang is an efficient, concise and high-performance programming language. Its main feature is its superiority over other languages ​​in terms of code execution speed. Routing in Golang is an important part of web development and requires routing to map requests to the correct handler. This article will introduce how to use Golang to implement routing.

1. Create a basic HTTP server
First, we need to create a basic HTTP server on the local computer.

package main

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

func main() {
    http.HandleFunc("/", hello)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func hello(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, World!")
}

The above code starts an HTTP server using Go's built-in http package. Use the http.HandleFunc function to specify the handler to send the request to, and use the http.ListenAndServe function to start the server on port 8080.

2. Add routing
The above code can only handle the root path. Now we will add another handler to handle other paths.

package main

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

func main() {
    http.HandleFunc("/", home)
    http.HandleFunc("/about", about)

    log.Fatal(http.ListenAndServe(":8080", nil))
}

func home(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Home Page")
}

func about(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "About Page")
}

In the above code, we use the http.HandleFunc function to define two handler functions: home and about. We also mapped them to the paths / and /about.

3. Use third-party libraries to implement routing

In Golang, there are also some third-party libraries that can help us implement routing. The most popular of these is the mux library.

To use mux to implement routing, we need to modify the above code as follows:

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {
    router := mux.NewRouter()
    router.HandleFunc("/", home)
    router.HandleFunc("/about", about)

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

func home(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Home Page")
}

func about(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "About Page")
}

In the above code, we used gorilla/muxLibrary to handle routing. We first create an instance of mux.Router. We then define two handler functions and bind them to the same paths as above.

4. Add dynamic routing

We can also set the routing to a dynamic path to handle requests similar to /user/10. In this case, 10 is the dynamic part and can be changed as needed.

We can use the mux.Vars() function to extract a value like 10 and send it back using the http.ResponseWriter function client.

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {
    router := mux.NewRouter()

    router.HandleFunc("/", home)
    router.HandleFunc("/about", about)

    // 添加动态路由
    router.HandleFunc("/user/{id}", func(w http.ResponseWriter, r *http.Request) {
        vars := mux.Vars(r)
        id := vars["id"]
        fmt.Fprintf(w, "User ID: %v", id)
    })

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

func home(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Home Page")
}

func about(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "About Page")
}

The above code maps the path /user/{id} to an anonymous function which extracts the "id" value and sends it back to the client.

5. Route grouping

Finally, we can group routes. This makes the code more manageable, especially in applications with many routes.

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/gorilla/mux"
)

func main() {
    router := mux.NewRouter()

    // 创建子路由器
    api := router.PathPrefix("/api").Subrouter()
    api.HandleFunc("/", apiHome)
    api.HandleFunc("/user", apiUser)

    // 添加其他路由
    router.HandleFunc("/", home)
    router.HandleFunc("/about", about)

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

func home(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Home Page")
}

func about(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "About Page")
}

func apiHome(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "API Home Page")
}

func apiUser(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "API User Page")
}

The above code shows how to use Subrouter() to create a subrouter and map it to the path /api. Additionally, we added other basic routing and handler functions.

6. Summary

In this article, we introduced the implementation method of routing in Go. We start by creating a basic HTTP server and then optimize the code using the gorilla/mux library. We also demonstrated how to use dynamic routing, how to group routes, and how to add handlers to routes.

Golang’s routing function is powerful and very easy to use. It helps developers build efficient, high-performance web applications while reducing development time and code complexity.

The above is the detailed content of Examples to explain how to use Golang to implement routing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn