Category Archives: Error

[HTTP] Solve the 406 not acceptable error

When a 406 error occurs, it means that it is a client error, and the client cannot parse the content returned by the server

Generally, in the accept header sent by the client, the allowed type is set, but the server does not return in this format

Accept represents the type of data that the sender (client) wants to accept.

If the type specified by accept is inconsistent with the content-type returned by the response, a 406, not acceptable error will occur

Modify the server to return in the specified format

Or modify the client to accept the format of the server

[Go] Solve the garbled content sent by go-smtp and the unparsed html mail sent

Use github.com/emersion/go-smtp to send notification email content through smtp

After adding the content of the html code, it will be displayed as it is in some mailboxes, and it is not displayed as html. The reason is that the Content-Type is not added.

tools/smtp.go

package tools

import (
    "encoding/base64"
    "github.com/emersion/go-sasl"
    "github.com/emersion/go-smtp"
    "strings"
)

func SendSmtp(server string, from string, password string, to []string, subject string, body string) error {
    auth := sasl.NewPlainClient("", from, password)
    subjectBase := base64.StdEncoding.EncodeToString([]byte(subject))
    msg := strings.NewReader(
        "From: " + from + "\r\n" +
            "To: " + strings.Join(to, ",") + "\r\n" +
            "Subject: =?UTF-8?B?" + subjectBase + "?=\r\n" +
            "Content-Type: text/html; charset=UTF-8" +
            "\r\n\r\n" +
            body + "\r\n")
    err := smtp.SendMail(server, auth, from, to, msg)
    if err != nil {
        return err
    }
    return nil
}

 

Test case

tools/smtp_test.go

package tools

import "testing"

func TestSendSmtp(t *testing.T) {
    body := "<a href=''>hello</a>"
    SendSmtp("smtp.sina.cn:25", "[email protected]", "xxxxx", []string{"[email protected]"}, "123456", body)
}

The current code is located under the tools package, that is, under the tools/ directory. When executing the test case, use the following command

go test tools/smtp.go tools/smtp_test.go

 

There is a tag in the content, and the result can be displayed normally in a connected form

Also note that my subject is base64 encoded

Subject: =?UTF-8?B?” + subjectBase + “?=\r\n

So that the subject part is not garbled, =?UTF-8?B? This is a fixed format in the mail protocol, for example, the following content, the middle part is the content after base64

=?UTF-8?B?5LiA5Y+35bqXNOWRqOW5tOW6hu+8jDEwMDDkuIfku7bng63plIA=?=

[Go] Solve panic: runtime error: invalid memory address or nil pointer dereference in golang

When a property or method is called on nil, a null pointer will be reported

Especially the structure pointer, this problem is very easy to occur, the following is the test code

package tools

import "fmt"

func MyTest() {
    type MConn struct {
        Name string
    }
    var conn * MConn
    var conn2 MConn
    conn3 := new (MConn)
    conn4 := & MConn{}
    fmt.Printf("%v,%v,%v,%v" , conn, conn2, conn3, conn4)
}

Return separately

<nil>,{},&{},&{}

When a structure pointer variable var conn *MConn is declared, but it is not initialized and the property is called directly, it will appear

panic: runtime error: invalid memory address or nil pointer dereference

Because conn is nil at this time, it is a null pointer

A null operation must be performed, if conn != nil {}

 

Of course, we sometimes do not make such an obvious error, but when we cooperate with map, this error may occur unintentionally.

    var mMap map[ string ]* MConn
    m1: = mMap[ " name " ]
    m1.Name = " qqq "

In this code map, when the key element does not exist, the zero value of value is returned, which happens to be *MConn. The zero value is nil, and an error will also be reported.

So the map has to be judged here

    var mMap map[ string ]* MConn
    m1, ok: = mMap[ " name " ]
     if ok {
        m1.Name = " qqq " 
    }

Git: How to Solve Error: Please commit your changes or stash them before you merge.

When the same file code is modified by the local branch and the remote branch, a file conflict will occur when the code of the remote branch is pulled

This error occurs Please commit your changes or stash them before you merge.

 

You can store the current content first, and git stash can store the current content in the stack

git stash and then git pull the new code

Then put out the content stored in the stack, git stash pop 

 

git stash list can view the list in the temporary storage stack

[Nginx] Configure nginx to support websocket to solve the problem of returning 400 error

When nginx is not configured to support webocket, but the domain name has been configured, such as: ws://gofly.sopans.com/ws_visitor 

Direct js connection will return a 400 error

 

You need to add these three headers under the nginx location block to upgrade the http connection to a websocket connection

proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection “Upgrade”;

 

For example, I open source customer gofly in

server{
       listen 80 ;
        server_name gofly.sopans.com;
        access_log /var/log/nginx/ gofly.sopans.com.access.log main;
        client_max_body_size 10M;
        location /static {
                root /var/www/html/go- fly;
        } 
        location / {
                proxy_pass http://127.0.0.1:8081;
                    proxy_http_version 1.1 ;
                    proxy_set_header X-Real- IP $remote_addr;
                    proxy_set_header Upgrade $http_upgrade;
                    proxy_set_header Connection "upgrade" ;
        }
}

[GO] The entry file under the main package in golang calls other go file functions and appears undefined

It is recommended that there is only one entry file for main.go under the golang main package

When there are other go files, and functions are defined in other go files

 

This function is called in the main.go entry file, go run main.go is executed, it will prompt undefined

If you have to do this, then all files must be added when go run, otherwise only the main.go file will be loaded by default

Only files in the non-main package will be automatically loaded through dependencies. So you need to enter multiple files as parameters

 

Should use go run a.go b.go c.go or go run *.go to run, compile the same

[Go] Solve the problem of exec: “gcc” executable file not found in %PATH% error when using cgo

Download the compressed package that matches your own system version

https://sourceforge.net/projects/mingw-w64/files/mingw-w64/

I am 64 bit, download this version

 

 After decompressing directly, put the bin directory into the PATH environment variable.

 If you are using goland ide development

To restart goland, if it still doesn’t work, use the system’s own cli window first

[Go] Testing when solving go test: warning: no tests to run

When executing a specified function of go test, the report: testing: warning: no tests to run

For example go test -v -run Mytest

 

The test file name must be this _test suffix

xxxx_test.go

 

If it is not designated to run by correspondence, then the test function must start with Test

For example, the following file can

package tools

import (
    " fmt " 
    " testing "
)

func TestMytest(t * testing.T) {
    Mytest()
}
func Mytest() {
    m: = make(map[ string ] string )
    m[ " a " ] = " b "

    m2: = make(map[ string ] interface {})
    m2[ " a " ] = " b "
    test(m2)
    a: = " aaa "
    test2(a)
}

func test(t map[ string ] interface {}) {
    fmt.Printf( " %T " , t)
}
func test2(t interface {}) {
    fmt.Printf( " %T " , t)
}

 There are two ways of execution

 

go test -v test_test.go

go test -v -run Mytest

[Go] Solve the empty interface interface{} cannot use (type []string) as type []interface {}

Empty interface{}

Can store any type of data

But when working with slices and maps, pay attention

[]interface{} or map[string]interface{}

 

May make this mistake cannot use (type []string) as type []interface {}

You cannot convert []T to []interface, nor can you convert map[string]T to map[string]interface{}

 

The Go language specification does not allow this because the two types do not have the same representation in memory.

Need to define separately []interface{} map[string]interface{}

Copy the element you want to convert to the above type

 For example, the following error:

[Go] Solve the fatal error: concurrent map writes map is not concurrently safe

Map is not concurrently safe, when there are multiple concurrent groutines reading and writing the same map 

Panic error will occur

concurrent map writes

 

For example, the following code will cause this error:

var mMap map[ int ] int

func TestMyMap(t * testing.T) {
    mMap = make(map[ int ] int )

    for i := 0 ; i < 5000 ; i++ {
        go func() {
            mMap[i] = i
        }()
        go readMap(i)
    }
}
func readMap(i int ) int {
     return mMap[i]
}

There are many ways to solve this error. Now we take the way of read-write lock.

Concurrent access to the map is not safe, and undefined behavior will occur, causing the program to exit. Therefore, if you want to access the map concurrently in a multi-coroutine, you must provide a synchronization mechanism. Generally, the concurrent access control to the map is achieved through the read-write lock sync.RWMutex, and the map and sync.RWMutex can be encapsulated to achieve the map Secure concurrent access

Transformed code

type SMap struct {
    sync.RWMutex
    Map map[ int ] int
}

func (l *SMap) readMap(key int ) ( int , bool ) {
    l.RLock()
    value, ok: = l.Map[key]
    l.RUnlock()
    return value, ok
}

func (l *SMap) writeMap(key int , value int ) {
    l.Lock()
    l.Map[key] = value
    l.Unlock()
}

var mMap * SMap

func TestMyMap(t * testing.T) {
    mMap = & SMap{
        Map: make(map[ int ] int ),
    }

    for i := 0 ; i < 5000 ; i++ {
        go func() {
            mMap.writeMap(i, i)
        }()
        go readMap(i)
    }
}
func readMap(i int ) ( int , bool ) {
     return mMap.readMap(i)
}

 There are three ways:

1. Use channel
2. Use sync.map
3. Use map but must be locked

[Go] Solve missing go.sum entry for module providing package

When a third-party library is used in the code, but the go.mod is not updated

This error will be reported if you run or build directly

missing go.sum entry for module providing package <package_name>

 

You can use go mod tidy to organize dependencies

 

This command will:

Remove unnecessary dependencies

Download the new dependency package

Update go.sum