Golang HTTP Basic Authentication mechanism example detailed _golang

Source: Internet
Author: User
Tags auth base64

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.