在我的代码中,我想根据用户身份验证级别禁用一些输入字段,我可以在 JavaScript 中做到这一点,但这是不推荐的解决方案,我想从服务器端做到这一点。
以下是我的go代码;
package main
import (
"context"
"html/template"
"net/http"
"strings"
"time"
)
type User struct {
Flags string
Title string
}
type UsersPageData struct {
PageTitle string
Users []User
}
func requestTime(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
ctx = context.WithValue(ctx, "requestTime", time.Now().Format(time.RFC3339))
r = r.WithContext(ctx)
next.ServeHTTP(w, r)
})
}
func helloHandler(name string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var title string
if requestTime := r.Context().Value("requestTime"); requestTime != nil {
if str, ok := requestTime.(string); ok {
title = "\ngenerated at: " + str
}
}
master := strings.Join([]string{"admin", "user", "superuser", "read"}, " ")
admin := strings.Join([]string{"admin"}, " ")
user := strings.Join([]string{"user"}, " ")
tmpl := template.Must(template.ParseFiles("index.html"))
data := UsersPageData{
PageTitle: "Users list: " + title,
Users: []User{
{Flags: master, Title: "Everything"},
{Flags: admin, Title: "Administrator"},
{Flags: user, Title: "Normal user"},
},
}
tmpl.Execute(w, data)
})
}
func main() {
http.Handle("/john", requestTime(helloHandler("John")))
http.ListenAndServe(":8080", nil)
}
这是我的模板,包括 JS 代码;
<style>
.admin {
color: green;
}
.user {
color: red;
--btn-disable: 0;
}
[data-authorized="no"] {
/* Attribute has this exact value */
cursor: not-allowed;
pointer-events: none;
/*Button disabled - CSS color class*/
color: #c0c0c0;
background-color: rgb(229, 229, 229) !important;
}
ibeautiful
相关分类