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

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
主站蜘蛛池模板: 台安县| 渭南市| 宜宾县| 梅州市| 赤壁市| 英超| 红安县| 秦皇岛市| 盐亭县| 张家港市| 喜德县| 奇台县| 交城县| 许昌县| 巫山县| 文水县| 北票市| 上杭县| 登封市| 峨山| 宿州市| 上林县| 博罗县| 武定县| 澜沧| 察雅县| 九寨沟县| 新泰市| 台安县| 武威市| 蓬溪县| 旌德县| 宜良县| 大悟县| 武川县| 东阿县| 芮城县| 岳阳市| 莱州市| 普陀区| 怀柔区|