An example of this article describes the HTTP Basic authentication mechanism of Golang. Share to everyone for your reference, specific as follows:
Read the <
Request Response Process:
Copy Code code as follows:
==>
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 OK
Content-type:text/plain; Charset=utf-8
Implementation of Golang HTTP Basic authentication mechanism
Copy Code code as follows:
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)
}
}
I hope this article will help you with your go language program.