- Go Web Development Cookbook
- Arpit Aggarwal
- 166字
- 2021-08-27 19:01:11
How to do it…
In this recipe, we are going to update the HTTP server we created in the previous recipe by adding a BasicAuth function and modifying the HandleFunc to call it. Perform the following steps:
- Create http-server-basic-authentication.go and copy the following content:
package main
import
(
"crypto/subtle"
"fmt"
"log"
"net/http"
)
const
(
CONN_HOST = "localhost"
CONN_PORT = "8080"
ADMIN_USER = "admin"
ADMIN_PASSWORD = "admin"
)
func helloWorld(w http.ResponseWriter, r *http.Request)
{
fmt.Fprintf(w, "Hello World!")
}
func BasicAuth(handler http.HandlerFunc, realm string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request)
{
user, pass, ok := r.BasicAuth()
if !ok || subtle.ConstantTimeCompare([]byte(user),
[]byte(ADMIN_USER)) != 1||subtle.ConstantTimeCompare([]byte(pass),
[]byte(ADMIN_PASSWORD)) != 1
{
w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
w.WriteHeader(401)
w.Write([]byte("You are Unauthorized to access the
application.\n"))
return
}
handler(w, r)
}
}
func main()
{
http.HandleFunc("/", BasicAuth(helloWorld, "Please enter your
username and password"))
err := http.ListenAndServe(CONN_HOST+":"+CONN_PORT, nil)
if err != nil
{
log.Fatal("error starting http server : ", err)
return
}
}
- Run the program with the following command:
$ go run http-server-basic-authentication.go
推薦閱讀
- 計(jì)算機(jī)網(wǎng)絡(luò)與通信(第2版)
- 智慧城市:大數(shù)據(jù)、互聯(lián)網(wǎng)時(shí)代的城市治理(第4版)
- Windows Server 2003 Active Directory Design and Implementation: Creating, Migrating, and Merging Networks
- 網(wǎng)絡(luò)安全技術(shù)與解決方案(修訂版)
- 通信簡史:從信鴿到6G+
- Wireshark網(wǎng)絡(luò)分析就這么簡單
- Metasploit Penetration Testing Cookbook
- Mastering Dart
- Working with Legacy Systems
- 計(jì)算機(jī)網(wǎng)絡(luò)技術(shù)及應(yīng)用
- Android UI Design
- 一本書讀懂物聯(lián)網(wǎng)
- 局域網(wǎng)組成實(shí)踐
- 一本書讀懂TCP/IP
- 深入理解計(jì)算機(jī)網(wǎng)絡(luò)