Tình huống thực tế

Trong dự án Golang của tôi có 3 github repo: dd_backend, dd_mobile và dd_goshare. Mã nguồn của dd_backend và dd_mobile sẽ dùng (gọi) dd_goshare. Tôi đặt cả 3 github repo này là private.
Trong thư mục local git repo của dd_backend hay dd_mobile nếu tôi gõ lệnh go mod tidy thì sẽ báo lỗi như sau

remote: Invalid username or token.
Password authentication is not supported for Git operations.
fatal: Authentication failed for 'https://github.com/your-org/dd_goshare/'

Với your-org là tên tài khoản Github của tôi hoặc tổ chức mà tôi làm việc.

Vậy cần phải cấu hình github như thế nào để go mod tidy truy cập private git repo dd_goshare thành công?

Các bước thực hiện

1. tạo github classic token

Vào trang web https://github.com/settings/tokens tạo classic token

Generate classic token
Generate classic token
Tạo Access Token
Tạo Access Token

2. Cấu hình git sử dụng token vừa tạo

git config --global url."https://<USERNAME>:<TOKEN>@github.com/your-org".insteadOf "https://github.com/your-org"

<USERNAME> là tên tài khoản github của bạn
<TOKEN> là nội dung token bạn vừa tạo ở bước 1
your-org thay bằng tên tổ chức (organization) chứa git repo của bạn

Chú ý này: Nếu bạn đã cấu hình access token vài lần trước đây thì file ~/.gitconfig sẽ có nhiều dòng cấu hình chồng chéo nhau dẫn đến lỗi. Cách tốt nhất bạn mở file ~/.gitconfig bằng lệnh nano ~/.gitconfig rồi xóa những dòng có chứa [url ....] đi rồi mới chạy lại lệnh trên

3. Cấu hình biến môi trường go

Thiết lập biến môi trường cho Go để biết rằng các module này là private. Điều này nói cho Go biết không dùng proxy hoặc checksum server của Go cho các module trong namespace đó.

go env -w 'GOPRIVATE=github.com/your-org/*'

4. Thử lại truy cập vào private git repo

Đóng terminal, rồi mở lại để màn hình terminal mới thực sự được khởi động với những cấu hình mới. Sau đó gõ lệnh
go mod tidy
hoặc lệnh
git ls-remote https://github.com/your_org/dd_goshare

Nếu vẫn còn lỗi remote: Invalid username or token

Nếu bạn vẫn gặp lỗi này

remote: Invalid username or token. Password authentication is not supported for Git operations. fatal: Authentication failed for 'https://github.com/your-org/dd_goshare/

Hãy tạo lại github access key, rồi thử liệt kê các biến environment của go bằng lệnh go env kiểm tra xem có 2 biến

GONOPROXY='github.com/your-org/*'
GONOSUMDB='github.com/your-org/*'