本文实例讲述了golang的HTTP基本认证机制。分享给大家供大家参考,具体如下:
看了http权威指南>>第12章HTTP基本认证机制(本站下载地址:https://www.jb51.net/books/93254.html),感觉讲的蛮详细的,写了一个小小例子测试.
请求响应过程:
复制代码 代码如下:
==>
GET /hello HTTP/1.1
Host: 127.0.0.1:12345
==
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="Dotcoo User Login"
==>
GET /hello HTTP/1.1
Host: 127.0.0.1:12345
Authorization: Basic YWRtaW46YWRtaW5wd2Q=
==
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
golang HTTP基本认证机制的实现
复制代码 代码如下:
package main
import (
"fmt"
"io"
"net/http"
"log"
"encoding/base64"
"strings"
)
// hello world, the web server
func HelloServer(w http.ResponseWriter, req *http.Request) {
auth := req.Header.Get("Authorization")
if auth == "" {
w.Header().Set("WWW-Authenticate", `Basic realm="Dotcoo User Login"`)
w.WriteHeader(http.StatusUnauthorized)
return
}
fmt.Println(auth)
auths := strings.SplitN(auth, " ", 2)
if len(auths) != 2 {
fmt.Println("error")
return
}
authMethod := auths[0]
authB64 := auths[1]
switch authMethod {
case "Basic":
authstr, err := base64.StdEncoding.DecodeString(authB64)
if err != nil {
fmt.Println(err)
io.WriteString(w, "Unauthorized!\n")
return
}
fmt.Println(string(authstr))
userPwd := strings.SplitN(string(authstr), ":", 2)
if len(userPwd) != 2 {
fmt.Println("error")
return
}
username := userPwd[0]
password := userPwd[1]
fmt.Println("Username:", username)
fmt.Println("Password:", password)
fmt.Println()
default:
fmt.Println("error")
return
}
io.WriteString(w, "hello, world!\n")
}
func main() {
http.HandleFunc("/hello", HelloServer)
err := http.ListenAndServe(":12345", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
希望本文所述对大家Go语言程序设计有所帮助。
您可能感兴趣的文章:- golang实现http服务器处理静态文件示例
- 浅谈golang的http cookie用法
- golang编程入门之http请求天气实例
- golang设置http response响应头与填坑记录
- Go语言通过http抓取网页的方法
- go语言实现一个最简单的http文件服务器实例
- Go语言中利用http发起Get和Post请求的方法示例
- go语言实现简单http服务的方法
- Go语言的http/2服务器功能及客户端使用