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

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
主站蜘蛛池模板: 保定市| 建德市| 赞皇县| 阳东县| 梅州市| 林芝县| 吐鲁番市| 铜梁县| 赤城县| 都江堰市| 焦作市| 泊头市| 潢川县| 镇原县| 镇宁| 应城市| 英超| 许昌县| 合阳县| 怀仁县| 商水县| 驻马店市| 大足县| 安丘市| 宝兴县| 彭州市| 商南县| 古蔺县| 灵宝市| 邹平县| 丹阳市| 桦南县| 柳林县| 象山县| 静海县| 潞西市| 德格县| 兰考县| 白玉县| 正镶白旗| 托里县|