Buy Me a Coffee

[Golang] Code snippets - Semver comparison

To make the project backward-compatible, a common util function for comparing the semantic version is indispensable. Here is a Golang solution implemented by leveraging go-semver package. package utils import "github.com/coreos/go-semver/semver" // CompareSemanticVersion compares two string written in semver format // return 0 indicates that the first version equals to the second version // return 1 indicates that the first version is greater than the second version // return -1 indicates that the first version is less than the second version func CompareSemanticVersion(current, last string) int { if current == last { return 0 } currentVersion := semver.New(current) lastVersion := semver.New(last) if currentVersion.LessThan(*lastVersion) { return -1 } return 1 } The unit test: ...

[Windows] Enable Windows default SSH server

This topic is already well documented by mircosoft docs. You can find it from Get started with OpenSSH. Here I just want to give two tips for accelerating the setup. There are two ways to activate the open ssh server on Windows: from Windows Settings or PowerShell. Personally, I would recommend to use the PowerShell. Open the PowerShell as an Administrator. Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*' # Install server Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0 # Start the sshd service Start-Service sshd # OPTIONAL but recommended: Set-Service -Name sshd -StartupType 'Automatic' # Confirm the Firewall rule is configured. It should be created automatically by setup. Run the following to verify if (!(Get-NetFirewallRule -Name "OpenSSH-Server-In-TCP" -ErrorAction SilentlyContinue | Select-Object Name, Enabled)) { Write-Output "Firewall Rule 'OpenSSH-Server-In-TCP' does not exist, creating it..." New-NetFirewallRule -Name 'OpenSSH-Server-In-TCP' -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22 } else { Write-Output "Firewall rule 'OpenSSH-Server-In-TCP' has been created and exists." } When you try to connect the OpenSSH server, you’ll need to use ssh username@servername. The servername is your device’s IP address. For example, 192.168.1.5. The username may confuse you. But you can find it by typing whoami in PowerShell or Command. It may look like laptop-nbgksu9c\user. In the ~/.ssh/config file, you can configure it like ...

[Yarn] Unable to connect to github.com

Today when I cloned a new project and ran yarn install, the below error popped up. yarn install v1.22.17 [1/4] Resolving packages... [2/4] Fetching packages... error Command failed. Exit code: 128 Command: git Arguments: ls-remote --tags --heads git://github.com/WearyMonkey/ngtemplate-loader.git Directory: /home/xxx/source/github.com/xxx/xxx/app Output: fatal: unable to connect to github.com: github.com[0: 220.28.17.148]: errno=Connection timed out The solution is to execute the below command under the cloned git repository. git config --global url."https://".insteadOf git://

[Golang] Write a simple CLI program

I will show a simple example in this post. Let’s say the program called cli-example. package main import ( "flag" "fmt" "os" ) func main() { command := os.Args[1] os.Args = append(os.Args[:1], os.Args[2:]...) switch command { case "version": fmt.Println("1.1.1") } } The 1st argument will always be the binary name, so the command starts from the 2nd argument. If your app also needs the subcommand, then extract it from the 3rd argument, like docker image ls. ...

[Golang] Create Dockerfile for golang app

Containerizing the application is very popular nowadays and it makes the deployment so easy. This post will show how to create a Dockerfile for golang application. There are basically two steps in the Dockerfile: Build the golang program source code Containerize the golang app binary # Build source code FROM golang:1.18-alpine AS build WORKDIR /go/src/github.com/app COPY . . RUN go mod tidy RUN CGO_ENABLED=0 GOOS=linux go build -a -o main . # Containerize the binary FROM alpine COPY --from=build /go/src/github.com/app/main . EXPOSE 3500 CMD ["/main"] Exporting the port 3500 is because golang app listens to 3500. Here is just an example. ...

Bash Handbook (🚧Continuous Update)

1. Check if a file path represented by environment variable exists [[ "$(cat ${ENV_VARIABLE})" ]] || printf "env is not exported." 2. Get the file name from the full path echo "$basename -a /home/foo/abc.txt" # Output abc.txt 3. Extract the specific cell value from a table output For example, the output of the command nomad node status -address=https://127.0.0.1:4646 ID DC Name Class Drain Eligibility Status d88b0888 dc1 oscarzhou-B550-AORUS-ELITE-AX-V2 <none> false eligible ready If we want to get value of the datacenter dc1 where is [2,2] in the array. The solution is ...

[Golang] How to import a package on the specific version

In Golang, when a package is imported, by default the codebase of the package’s default branch will be used by the caller project. However, sometimes we want to import a package’s specific branch codebase. For example, the specific version fixed a bug where we can’t wait until the repository maintainer merges the pull request. So in this post, I will walk you through how to specify a package version in your Golang project. Let me take an example to help explain better. ...

Git Handbook (🚧Continuous Update)

1. Discard the changes git checkout -- . 2. Create a new branch git checkout -b <branch_name> # or git branch <branch_name> 3. Cache the password git config --global credential.helper store git config --global credential.helper cache 4. Stash the current changes git stash 5. Recovery/Apply the stash to the current branch git stash list git stash apply stash@{stash_index} # Most often we recover the stash@{0}, so we also can use below git stash apply 6. Configure username and email locally Sometime we need to configure a different username and email for the specific repository ...

[Dokku] Command Cheatsheet

A quick reference guide for commonly used Dokku commands. 1. Create and list app # Create app dokku apps:create <app_name> # List app dokku apps:list 2. Set domains # Set app's domain dokku domains:set <app_name> app.example.com # Set global domain dokku domains:set-global example.com 3. Join app to a specific network # List all networks dokku network:list # Add an app to a specific network dokku network:set <app_name> initial-network <target_network> 4. Show the app’s configuration dokku config:show <app_name> 5. Manully restart an app dokku ps:rebuild <app_name> 6. Bind app container to all interface bind to all interfaces (0.0.0.0), so the container can be accessed by external request. However, the host port will be randomly assigned. ...

[Dokku] How to set up dokku to deploy docker image

About installing the dokku, I have written another post before: How to install Dokku with Portainer. So I will assume that you have Dokku installed in your server in this post. 1. Environment Setting Dokku: version: 0.27.5. HTTP port: 80, HTTPS port: 443, SSH port: 5022 IP of remote server where the Dokku is installed: 166.23.44.25 (example) Domain: example.com Name of App that will be deployed by Dokku: blog Port of App: 3000 2. SSH Configuration Generate ssh key public file id_rsa.pub ssh-keygen -o We will name the file as dokku_rsa, then you will see two files are generated: dokku_rsa and dokku_rsa.pub. ...

DigitalOcean Referral Badge
Sign up to get $200, 60-day account credit !