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

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
主站蜘蛛池模板: 时尚| 潢川县| 和静县| 长泰县| 昌都县| 东丽区| 东丽区| 台东市| 丹凤县| 合江县| 襄城县| 仪征市| 准格尔旗| 姜堰市| 成安县| 廊坊市| 昌乐县| 弋阳县| 芮城县| 三穗县| 泰兴市| 阿坝县| 土默特左旗| 土默特左旗| 徐汇区| 津南区| 遂宁市| 河东区| 镇远县| 乌审旗| 五莲县| 兴安盟| 青州市| 万州区| 连南| 吉木萨尔县| 西畴县| 浦江县| 元谋县| 尼木县| 林周县|