Summary of snippets when developing with Go

Introduction

Here's a quick summary of the snippets I personally use when programming in Go. There are various types, from those that are used very often to those that are used only occasionally. It looks like it can be used! !! !! I would be happy if you could introduce just the ones that you thought!

Snippet registration with vscode

First of all, I will briefly introduce how to register snippets with vscode Code -> Preferences -> User Snippets スクリーンショット 2020-10-07 16.33.46.png ↓ Then a screen like this will appear, so click go スクリーンショット 2020-10-07 16.34.22.png ↓ Then the following json file will be displayed, so it is like adding the snippet you want to use there スクリーンショット 2020-10-07 16.34.44.png

Snippet registration syntax

Snippet registration can be done with the following syntax

python


"Snippet title": {
  "prefix": "What kind of characters should be typed as predictive conversion?", 
  "body": [
      "What kind of character string should be output?",
      "If you want to open a business, you can open it by entering it separated by commas like this",
  ],
  "description": "Detailed explanation"
},

About specifying the cursor position

You can also decide where to hold the cursor by entering the characters $ 1 after typing in the snippet. For example, when you create the following snippet

python


"Print to console": {
  "prefix": "fff",
  "body": ["fmt.Printf(\"==========%#v\\n\", $1)"],
  "description": "Log to check the movement"
},

After using the snippet

python


fmt.Printf("==========%#v\n", )
                        //↑ The cursor comes here

Will come to say

About other special characters

Character you want to insert Insertion method
$ \\$
tab \t
Double quote "
Single quote '

Snippet

--Debug print --Structure function

Debug print

This is a print for debugging. It is often used to check the contents of the structure and to identify the location of the error.

python


"Print to console": {
  "prefix": "fff",
  "body": ["fmt.Printf(\"==========%#v\\n\", $1)"],
  "description": "Log to check the movement"
},

fff

python


fmt.Printf("==========%#v\n", )

Structure function

I created it because it's too annoying to enter parentheses when creating a struct method. I personally use this too

python


"func": {
  "prefix": "fc",
  "body": ["func ($1) $2($3)($4){", "\t$0", "}"],
  "description": "Create a struct function"
},

fc

python


func () ()(){
	
}

package Just print package It's surprisingly easy!

python


"package": {
  "prefix": "pac",
  "body": "package",
  "description": "I don't even want to write a "package""
},

pac

python


package

Table driven test

It creates a template for table-driven testing at once. It's quite annoying to write from 0 every time, so I made it roughly first with this (For table-driven testing, click here](https://qiita.com/takehanKosuke/items/cbfc88c4b7956adede79))

python


"test func": {
  "prefix": "fct",
  "body": [
    "func Test$1(t *testing.T) {",
    "\tt.Parallel()",
    "\tasserts := assert.New(t)",
    "\ttests := []struct{",
    "\t\tname string",
    "\t\tinput string",
    "\t\toutput string",
    "\t}{",
    "\t\t{",
    "\t\t\tname: \"\",",
    "\t\t\tinput: \"\",",
    "\t\t\toutput: \"\",",
    "\t\t},",
    "\t}",
    "\tfor _, td := range tests {",
    "\t\ttd := td",
    "\t\tt.Run(fmt.Sprintf(\"$1: %s\", td.name), func(t *testing.T) {",
    "\t\t})",
    "\t}",
    "}"
  ],
  "description": "Table test base"
},

fct

python


func Test(t *testing.T) {
	t.Parallel()
	asserts := assert.New(t)
	tests := []struct{
		name string
		input string
		output string
	}{
		{
			name: "",
			input: "",
			output: "",
		},
	}
	for _, td := range tests {
		td := td
		t.Run(fmt.Sprintf(": %s", td.name), func(t *testing.T) {
		})
	}
}

gomock It is a command that you will definitely write in gomock, which is a mock library often used in go. It's useful because it's easy to forget how to draw it.

python


"Gomock template": {
  "prefix": "tgomock",
  "body": [
    "//gomock settings",
    "ctrl := gomock.NewController(t)",
    "defer ctrl.Finish()"
  ],
  "description": "Create ginContext for test"
},

tgomock

python


//gomock settings
ctrl := gomock.NewController(t)
defer ctrl.Finish()

Test gin context

This is a snippet used when writing tests including gin context in gin, which is a framework of go (see here for details).

python


"test gin Context": {
  "prefix": "tgincontext",
  "body": [
    "//Generating a gin context for test",
    "ginContext, _ := gin.CreateTestContext(httptest.NewRecorder())",
    "req, _ := http.NewRequest(\"GET\", \"/\", nil)",
    "//req.Header.Add(\"Authorization\", td.inputHeader)",
    "//req.Header.Add(\"Authorization\", td.inputHeader)",
    "ginContext.Request = req"
  ],
  "description": "Initial fixed phrase for gomock"
},

tgincontext

python


//Generating a gin context for test
ginContext, _ := gin.CreateTestContext(httptest.NewRecorder())
req, _ := http.NewRequest("GET", "/", nil)
//req.Header.Add("Authorization", td.inputHeader)
//req.Header.Add("Authorization", td.inputHeader)
ginContext.Request = req

http request

This is a snippet used when skipping http requests with go. It's easy to forget how to add headers and parameters, so I always remember using this.

python


"HTTP GET request": {
  "prefix": "httpget",
  "body": [
    "url := \"\"",
    "req, err := http.NewRequest(\"GET\", url, nil)",
    "if err != nil{",
    "\treturn nil, err",
    "}",
    "//header",
    "req.Header.Add(\"\", \"\")",
    "//Query parameters",
    "params := req.URL.Query()",
    "params.Add(\"\",\"\")",
    "req.URL.RawQuery = params.Encode()"
  ],
  "description": "HTTP GET request"
}

httpget

python


url := ""
req, err := http.NewRequest("GET", url, nil)
if err != nil{
	return nil, err
}
//header
req.Header.Add("", "")
//Query parameters
params := req.URL.Query()
params.Add("","")
req.URL.RawQuery = params.Encode()

At the end

Personally, snippets are fixed phrases, but many of them are made for things that tend to forget detailed setting methods. I think I will use this often in the future! I would like to add more information as needed!

Recommended Posts

Summary of snippets when developing with Go
Summary of problems when doing Semantic Segmentation with Pytorch
Summary of go json conversion behavior
A Tour of Go Learning Summary
Memorandum of Understanding when migrating with GORM
Summary of operations often performed with asyncpg
Recommended environment and usage when developing with Python
Hello world with full features of Go language
Python with Go
[Python] Summary of S3 file operations with boto3
Summary of frequently used commands (with petit commentary)
Summary of error handling methods when installing TensorFlow (2)
Summary of reference sites when editing Blender Script with an external editor (VS Code)
Summary of tools for operating Windows GUI with Python
Perform multiple version control of Go with anyenv + goenv
Summary of Pandas methods used when extracting data [Python]
Summary of the basic flow of machine learning with Python
Summary of things that were convenient when using pandas
Things to do when you start developing with Django
Summary of how to share state with multiple functions
Precautions when operating with string for TmeStampType of PySpark
Summary when using Fabric
Summary of Tensorflow / Keras
Summary of pyenv usage
Summary of string operations
Features of Go language
Summary of Python arguments
Summary of logrotate software logrotate
Summary of test method
Format summary of formats that can be serialized with gensim
Settings when developing App Engine / Python apps with VS Code
Code snippets often used when processing videos with Google Colaboratory
Code snippets often used when using BigQuery with Google Colab
[For beginners] Summary of standard input in Python (with explanation)
Xpath summary when extracting data from websites with Python Scrapy
Sample code summary when working with Google Spreadsheets from Google Colab
A collection of methods used when aggregating data with pandas
Basic summary of data manipulation with Python Pandas-First half: Data creation & manipulation
[Memo to add] Page to see when developing with GAE / P
When developing with ipython, scrapy can no longer be read
Here's a summary of things that might be useful when dealing with complex numbers in Python