Home  >  Article  >  Backend Development  >  golang gets request address

golang gets request address

WBOY
WBOYOriginal
2023-05-14 19:36:361103browse

When writing web applications using Golang, sometimes you need to obtain the request address (URL) entered by the user in the browser. This process is very simple, just use Go's built-in net/http package to complete.

First, we need to create an HTTP handler. Can be extended based on existing HTTP handlers or written from scratch. The following is a simple HTTP handler example, which just returns a "Hello, World!" message:

package main

import (
    "fmt"
    "net/http"
)

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, "Hello, World!")
    })
    http.ListenAndServe(":8080", nil)
}

The http.HandleFunc function in the code implements a router, which The request is mapped to the handler function, and the http.ListenAndServe function starts the HTTP server on port 8080.

Next, we need to get the request URL from the http.Request request object. In the handler function, it can be obtained via r.URL. Note that URL is a structure, we need to use its String() method to convert it to string form. The following is the code to get the request URL:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Your request URL path is: %s", r.URL.String())
})

The above code prints the path part of the request URL (that is, the part after "/") into the HTTP response.

If we need to get the complete request URL (including query string, etc.), then we can use the r.URL.RequestURI() method:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Your request URL is: %s", r.URL.RequestURI())
})

The above code Will print the full request URL to the HTTP response.

In addition to obtaining the request URL, the http.Request object also provides a lot of other information, such as request method, request header, request body, etc. Through them, we can write more flexible and feature-rich HTTP handlers.

Summary:

Getting the request address in Golang is very simple, just use the URL or RequestURI in the http.Request object method is enough. As developers, we should be familiar with these basic HTTP information in order to control our web applications more granularly.

The above is the detailed content of golang gets request address. 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