ZBLOG

golang http client basic auth

Here is an example of using basic authentication with the Go HTTP client:

package main

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

func main() {
	// Set up basic auth credentials
	username := "username"
	password := "password"
	auth := username + ":" + password
	basicAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))

	// Create a new request
	req, err := http.NewRequest("GET", "https://example.com/api/resource", bytes.NewBuffer(nil))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	// Add basic auth header to the request
	req.Header.Set("Authorization", basicAuth)

	// Send the request
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}

	// Read the response body
	defer resp.Body.Close()
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response body:", err)
		return
	}

	// Print the response body
	fmt.Println(string(body))
}

This code sets up the basic auth credentials for the desired user and password, creates a new GET request with an empty body, adds the basic auth header to the request, sends the request using the HTTP client, reads the response body, and prints it to the console.

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=504

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?