官术网_书友最值得收藏!

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:

  1. 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
}
}
  1. Run the program with the following command:
$ go run http-server-basic-authentication.go
主站蜘蛛池模板: 巴林左旗| 通州区| 申扎县| 泽州县| 定州市| 民勤县| 巴塘县| 米易县| 镇江市| 四子王旗| 昌吉市| 五河县| 沙雅县| 开封县| 临泽县| 密云县| 汤阴县| 特克斯县| 宽甸| 龙游县| 鸡泽县| 盐边县| 叙永县| 彭州市| 环江| 湾仔区| 武宣县| 宁夏| 眉山市| 太仆寺旗| 抚松县| 叙永县| 那坡县| 略阳县| 疏附县| 龙州县| 宁都县| 孟州市| 荔浦县| 蒲江县| 土默特左旗|