← 中文资源

简体中文版本

SetBasicAuth 构造 Basic Auth 头

SetBasicAuth 帮你写好标准 Authorization 头:凭据是 user:password 的 base64,冒号分隔,解码后可用 Cut 还原用户名与密码。

阅读英文原文

实现说明

SetBasicAuth 构造 Basic Auth 头以函数 main为骨架。 err 在 2 处被测试,非 nil 就以 panic(err) 中止运行。

使用要点

  • 失败路径是 panic(err)——没有可检查的错误返回值,示例里也没有任何恢复机制。
  • 跑完文件,输出里会留下标记——scheme:、credentials:、user:。

常见问题

调用失败时会发生什么?

这里没有错误返回值:非 nil 的 err 会立即走到 panic(err)。

运行「SetBasicAuth 构造 Basic Auth 头」会打印什么?

运行文件本身,scheme:、credentials:、user: 这些前缀各对应一段演示逻辑。

核心语句

if err != nil {
	panic(err)
}

代码示例

package main

import (
	"encoding/base64"
	"fmt"
	"net/http"
	"strings"
)

func main() {
	req, err := http.NewRequest(http.MethodGet, "https://api.example.test/v1/orders", nil)
	if err != nil {
		panic(err)
	}

	// SetBasicAuth writes the standard Authorization header for you
	req.SetBasicAuth("svc-orders", "s3cret-token")
	header := req.Header.Get("Authorization")
	scheme, credentials, _ := strings.Cut(header, " ")
	fmt.Println("scheme:", scheme)
	fmt.Println("credentials:", credentials)

	// the credentials are base64 of user:password with a single colon
	decoded, err := base64.StdEncoding.DecodeString(credentials)
	if err != nil {
		panic(err)
	}
	user, pass, ok := strings.Cut(string(decoded), ":")
	fmt.Println("user:", user, "| password found:", ok, "| pass length:", len(pass))
}