- 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
推薦閱讀
- 黑客攻防實戰(zhàn)技術(shù)完全手冊:掃描、嗅探、入侵與防御
- 6G潛在關(guān)鍵技術(shù)(下冊)
- 物聯(lián)網(wǎng)智慧安監(jiān)技術(shù)
- 網(wǎng)管員典藏書架:網(wǎng)絡(luò)管理與運維實戰(zhàn)寶典
- Wireshark網(wǎng)絡(luò)分析就這么簡單
- React:Cross-Platform Application Development with React Native
- CCNP TSHOOT(642-832)認證考試指南
- Unity Artificial Intelligence Programming
- Android UI Design
- Dart Cookbook
- 華為HCIA-Datacom認證指南
- 精通SEO:100%網(wǎng)站流量提升密碼
- 區(qū)塊鏈技術(shù)與應(yīng)用:打造分布式商業(yè)新生態(tài)
- 智能物聯(lián)網(wǎng):區(qū)塊鏈與霧計算融合應(yīng)用詳解
- 互聯(lián)網(wǎng)視覺設(shè)計(全彩慕課版)