search
HomeBackend DevelopmentGolanggolang http get garbled code

In recent years, with the popularity of Go language, more and more people have begun to use Go language to develop Web applications, including programs that use HTTP for network access. However, encountering garbled characters in HTTP GET requests is a common problem. This article will explore this problem, its possible causes, and provide some solutions.

1. Problem description

When using Go language to write HTTP GET requests, sometimes we encounter the problem of garbled text. The main symptom is that the response body returned by the request contains garbled characters instead of the expected results.

2. Cause of the problem

There may be many reasons for garbled HTTP GET requests. Here are some common reasons:

1. The correct character set is not used. . In the response header of the HTTP request, the server will return the character set of the document. If we do not parse this value correctly, it may cause encoding problems.

2. No character set specified. Sometimes the server does not provide character set information. If we do not specify a character set, it may cause encoding problems.

3. Character set does not match. Sometimes, the character sets in the request header and response header do not match, which may result in garbled characters.

4. When reading data from a file, the encoding specified is inconsistent with the actual encoding, which may also lead to garbled characters.

3. Solution

1. Check the character set of the server response

: In HTTP GET, the server's response header contains character set information. If we don't check and parse this value correctly, it may cause garbled characters. The correct way is to use the resp.Header.Get("Content-Type") method provided in the Go language's net/http library to obtain the Content-Type response header information and obtain the character set value from it. We then need to use this charset to convert the response body to the correct string. For example, if the character set in the response header is UTF-8, we can use the following method to convert the response body into a UTF-8 encoded string.

import (
    "io/ioutil"
    "net/http"
)

func main() {
    resp, err := http.Get("http://example.com/")
    if err != nil {
        // handle error
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        // handle error
    }

    contentType := resp.Header.Get("Content-Type")
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }

    // convert body bytes to string
    var content string
    if strings.Contains(contentType, "UTF-8") {
        content = convertToString(string(body), "UTF-8", "UTF-8")
    } else {
        content = convertToString(string(body), contentType, "UTF-8")
    }
}

func convertToString(content string, srcEncoding string, destEncoding string) string {
    srcDecoder := charmap.Windows1252.NewDecoder()
    srcReader := strings.NewReader(content)
    srcReader.Reset(content)
    srcUTF8Reader := transform.NewReader(srcReader, srcDecoder)
    destDecoder := charmap.ISO8859_1.NewDecoder()
    destWriter := new(bytes.Buffer)
    destUTF8Writer := transform.NewWriter(destWriter, destDecoder)
    io.Copy(destUTF8Writer, srcUTF8Reader)
    return destWriter.String()
}

2. Specify the correct character set

When sending an HTTP GET request, we should specify the character set in the request header. In this case, we need to use the Req.Header.Set("Content-Type", "text/html; charset=UTF-8") method provided in the Go language's net/http library to specify the Content-Type. For example, if we wish to send UTF-8 text using UTF-8 encoding, we can use the following code:

import (
    "net/http"
)

func main() {
    client := http.Client{}
    req, err := http.NewRequest("GET", "http://example.com/", nil)
    if err != nil {
        // handle error
    }

    req.Header.Set("Content-Encoding", "gzip")
    req.Header.Set("Content-Type", "text/html; charset=UTF-8")

    resp, err := client.Do(req)
    if err != nil {
        // handle error
    }
    defer resp.Body.Close()
}

3.Character Set Conversion

If we specify the correct character set, but still If you encounter garbled characters, you may need to perform character set conversion on the returned content. We can use the transform.String() method provided in the golang.org/x/text/transform library of the Go language to convert strings. For example, suppose we read an ISO-8859-1 encoded text from the file, but the server returned UTF-8 encoded text, we can use the following code to convert:

import (
    "bytes"
    "io"
    "io/ioutil"
    "net/http"
    "golang.org/x/text/transform"
    "golang.org/x/text/encoding/charmap"
)

func main() {
    resp, err := http.Get("http://example.com/")
    if err != nil {
        // handle error
    }
    defer resp.Body.Close()

    if resp.StatusCode != http.StatusOK {
        // handle error
    }

    // read body
    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        // handle error
    }

    // convert body bytes to string
    s, _, err := transform.String(charmap.ISO8859_1.NewDecoder().Transformer(), string(body))
    if err != nil {
        // handle error
    }

    // do something with s
    ...
}

4. Conclusion

Garbled characters in HTTP GET requests may affect the results of your network requests. If you encounter this problem, first check the character set information, and then check that the character set is specified correctly. If none of the above solves your problem, you may need to perform a character set conversion. I hope the methods provided in this article can help you solve the garbled problem in HTTP GET requests.

The above is the detailed content of golang http get garbled code. 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
Implementing Mutexes and Locks in Go for Thread SafetyImplementing Mutexes and Locks in Go for Thread SafetyMay 05, 2025 am 12:18 AM

In Go, using mutexes and locks is the key to ensuring thread safety. 1) Use sync.Mutex for mutually exclusive access, 2) Use sync.RWMutex for read and write operations, 3) Use atomic operations for performance optimization. Mastering these tools and their usage skills is essential to writing efficient and reliable concurrent programs.

Benchmarking and Profiling Concurrent Go CodeBenchmarking and Profiling Concurrent Go CodeMay 05, 2025 am 12:18 AM

How to optimize the performance of concurrent Go code? Use Go's built-in tools such as getest, gobench, and pprof for benchmarking and performance analysis. 1) Use the testing package to write benchmarks to evaluate the execution speed of concurrent functions. 2) Use the pprof tool to perform performance analysis and identify bottlenecks in the program. 3) Adjust the garbage collection settings to reduce its impact on performance. 4) Optimize channel operation and limit the number of goroutines to improve efficiency. Through continuous benchmarking and performance analysis, the performance of concurrent Go code can be effectively improved.

Error Handling in Concurrent Go Programs: Avoiding Common PitfallsError Handling in Concurrent Go Programs: Avoiding Common PitfallsMay 05, 2025 am 12:17 AM

The common pitfalls of error handling in concurrent Go programs include: 1. Ensure error propagation, 2. Processing timeout, 3. Aggregation errors, 4. Use context management, 5. Error wrapping, 6. Logging, 7. Testing. These strategies help to effectively handle errors in concurrent environments.

Implicit Interface Implementation in Go: The Power of Duck TypingImplicit Interface Implementation in Go: The Power of Duck TypingMay 05, 2025 am 12:14 AM

ImplicitinterfaceimplementationinGoembodiesducktypingbyallowingtypestosatisfyinterfaceswithoutexplicitdeclaration.1)Itpromotesflexibilityandmodularitybyfocusingonbehavior.2)Challengesincludeupdatingmethodsignaturesandtrackingimplementations.3)Toolsli

Go Error Handling: Best Practices and PatternsGo Error Handling: Best Practices and PatternsMay 04, 2025 am 12:19 AM

In Go programming, ways to effectively manage errors include: 1) using error values ​​instead of exceptions, 2) using error wrapping techniques, 3) defining custom error types, 4) reusing error values ​​for performance, 5) using panic and recovery with caution, 6) ensuring that error messages are clear and consistent, 7) recording error handling strategies, 8) treating errors as first-class citizens, 9) using error channels to handle asynchronous errors. These practices and patterns help write more robust, maintainable and efficient code.

How do you implement concurrency in Go?How do you implement concurrency in Go?May 04, 2025 am 12:13 AM

Implementing concurrency in Go can be achieved by using goroutines and channels. 1) Use goroutines to perform tasks in parallel, such as enjoying music and observing friends at the same time in the example. 2) Securely transfer data between goroutines through channels, such as producer and consumer models. 3) Avoid excessive use of goroutines and deadlocks, and design the system reasonably to optimize concurrent programs.

Building Concurrent Data Structures in GoBuilding Concurrent Data Structures in GoMay 04, 2025 am 12:09 AM

Gooffersmultipleapproachesforbuildingconcurrentdatastructures,includingmutexes,channels,andatomicoperations.1)Mutexesprovidesimplethreadsafetybutcancauseperformancebottlenecks.2)Channelsofferscalabilitybutmayblockiffullorempty.3)Atomicoperationsareef

Comparing Go's Error Handling to Other Programming LanguagesComparing Go's Error Handling to Other Programming LanguagesMay 04, 2025 am 12:09 AM

Go'serrorhandlingisexplicit,treatingerrorsasreturnedvaluesratherthanexceptions,unlikePythonandJava.1)Go'sapproachensureserrorawarenessbutcanleadtoverbosecode.2)PythonandJavauseexceptionsforcleanercodebutmaymisserrors.3)Go'smethodpromotesrobustnessand

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor