本文实例讲述了golang的http基本认证机制。分享给大家供大家参考,具体如下:
看了<<http权威指南>>第12章http基本认证机制(本站下载地址:),感觉讲的蛮详细的,写了一个小小例子测试.
请求响应过程:
==>
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语言程序设计有所帮助。
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
-
Go打包二进制文件的实现
背景众所周知,go语言可打包成目标平台二进制文件是其一大优势,如此go项目在服务器不需要配置go环境和依赖就可跑起来。操作需求:打包部署到centos7笔者打包...
[阅读全文]
-
-
-
-
golang语言编码规范的实现
本规范旨在为日常go项目开发提供一个代码的规范指导,方便团队形成一个统一的代码风格,提高代码的可读性,规范性和统一性。本规范将从命名规范,注释规范,代码风格和 ...
[阅读全文]
-
-
-
-
网友评论