运行我的Go程序时,它会发生混乱并返回以下内容:
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x38 pc=0x26df]
goroutine 1 [running]:
main.getBody(0x1cdcd4, 0xf800000004, 0x1f2b44, 0x23, 0xf84005c800, ...)
/Users/matt/Dropbox/code/go/scripts/cron/fido.go:65 +0x2bb
main.getToken(0xf84005c7e0, 0x10)
/Users/matt/Dropbox/code/go/scripts/cron/fido.go:140 +0x156
main.main()
/Users/matt/Dropbox/code/go/scripts/cron/fido.go:178 +0x61
goroutine 2 [syscall]:
created by runtime.main
/usr/local/Cellar/go/1.0.3/src/pkg/runtime/proc.c:221
goroutine 3 [syscall]:
syscall.Syscall6()
/usr/local/Cellar/go/1.0.3/src/pkg/syscall/asm_darwin_amd64.s:38 +0x5
syscall.kevent(0x6, 0x0, 0x0, 0xf840085188, 0xa, ...)
/usr/local/Cellar/go/1.0.3/src/pkg/syscall/zsyscall_darwin_amd64.go:199 +0x88
syscall.Kevent(0xf800000006, 0x0, 0x0, 0xf840085188, 0xa0000000a, ...)
/usr/local/Cellar/go/1.0.3/src/pkg/syscall/syscall_bsd.go:546 +0xa4
net.(*pollster).WaitFD(0xf840085180, 0xf840059040, 0x0, 0x0, 0x0, ...)
/usr/local/Cellar/go/1.0.3/src/pkg/net/fd_darwin.go:96 +0x185
net.(*pollServer).Run(0xf840059040, 0x0)
/usr/local/Cellar/go/1.0.3/src/pkg/net/fd.go:236 +0xe4
created by net.newPollServer
/usr/local/Cellar/go/1.0.3/src/pkg/net/newpollserver.go:35 +0x382 …Run Code Online (Sandbox Code Playgroud) 我正在寻找一小部分限速中间件:
然后,我可以围绕身份验证路由或其他可能容易遭受暴力攻击的路由(即使用过期的令牌密码重置URL等).有人粗暴地强制使用16或24字节令牌的可能性非常低,但是进行额外步骤并没有什么坏处.
我查看了https://code.google.com/p/go-wiki/wiki/RateLimiting,但我不确定如何将其与http.Request(s)进行协调.此外,我不确定在任何时间段内我们如何"跟踪"来自给定IP的请求.
理想情况下,我最终得到类似的东西,注意我是在反向代理(nginx)的后面,所以我们正在检查REMOTE_ADDRHTTP头而不是使用r.RemoteAddr:
// Rate-limiting middleware
func rateLimit(h http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
remoteIP := r.Header.Get("REMOTE_ADDR")
for req := range (what here?) {
// what here?
// w.WriteHeader(429) and close the request if it exceeds the limit
// else pass to the next handler in the chain
h.ServeHTTP(w, r)
}
}
// Example routes
r.HandleFunc("/login", use(loginForm, rateLimit, csrf)
r.HandleFunc("/form", use(editHandler, rateLimit, csrf)
// Middleware …Run Code Online (Sandbox Code Playgroud) 我想看看是否有一种更好(更快,更有条理)的方式在Go中拆分我的模板.我非常喜欢坚持使用html/template(或其包装),因为我相信它的安全模型.
template.ParseGlob用来解析内部的所有模板文件init().$title在每个模板(即listing_payment.tmpl)中设置了一个并将其传递给内容模板.html/template解析后会在内存中缓存模板t.ExecuteTemplate(w, "name.tmpl", map[string]interface{})并且不对每个请求进行任何愚蠢的解析.我从多个部分组成模板(这是我发现笨重的一点),如下所示:
{{ $title := "Page Title" }}
{{ template "head" $title }}
{{ template "checkout" }}
{{ template "top" }}
{{ template "sidebar_details" . }}
{{ template "sidebar_payments" }}
{{ template "sidebar_bottom" }}
<div class="bordered-content">
...
{{ template "listing_content" . }}
...
</div>
{{ template "footer"}}
{{ template "bottom" }}
Run Code Online (Sandbox Code Playgroud)我的三个问题是:
这是性能,还是多个{{ template "name" }}标签会导致潜在的每次请求性能下降?write - broken …
上周这篇文章受到了一些启发,我正在重构一个应用程序,我必须更明确地将上下文(数据库池,会话存储等)传递给我的处理程序.
但是,我遇到的一个问题是,如果没有全局模板映射,ServeHTTP我的自定义处理程序类型(满足http.Handler)上的方法将无法再访问映射以呈现模板.
我需要保留全局templates变量,或者将我的自定义处理程序类型重新定义为结构.
有没有更好的方法来实现这一目标?
func.go
package main
import (
"fmt"
"log"
"net/http"
"html/template"
"github.com/gorilla/sessions"
"github.com/jmoiron/sqlx"
"github.com/zenazn/goji/graceful"
"github.com/zenazn/goji/web"
)
var templates map[string]*template.Template
type appContext struct {
db *sqlx.DB
store *sessions.CookieStore
}
type appHandler func(w http.ResponseWriter, r *http.Request) (int, error)
func (ah appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// templates must be global for us to use it here
status, err := ah(w, r)
if err != nil {
log.Printf("HTTP %d: %q", status, err) …Run Code Online (Sandbox Code Playgroud) TL; DR:如何在不事先metav1.ObjectMeta知道k8s API对象的情况下灵活地对其进行解码并检查其顶层结构Kind?
我正在编写一个准入控制器端点,该端点根据字段将metav1.AdmissionReview对象的Request.Object.Raw字段解组为具体的对象Request.Kind-例如
if kind == "Pod" {
var pod core.Pod
// ...
if _, _, err := deserializer.Decode(admissionReview.Request.Object.Raw, nil, &pod); err != nil {
return nil, err
}
annotations := pod.ObjectMeta.Annotations
// inspect/validate the annotations...
Run Code Online (Sandbox Code Playgroud)
这需要map[kind]corev1.Object预先知道所有可能的类型,或者要求用户提供我们可以使用的更灵活的类型。
我想实现的目标更接近:
var objMeta core.ObjectMeta
if _, _, err := deserializer.Decode(admissionReview.Request.Object.Raw, nil, &objMeta); err != nil {
return nil, err
}
// if objMeta is populated, validate the fields, else …Run Code Online (Sandbox Code Playgroud) 我期待遍历一个struct的字符串字段,所以我可以做一些清理/验证(与strings.TrimSpace,strings.Trim等).
现在我有一个凌乱的交换机案例,它不是真正可扩展的,因为这不是我的应用程序(网络表单)的热点,它似乎利用reflect是一个很好的选择.
然而,我对如何实现这个问题有一些障碍,而且反射文档对我来说有点混乱(我一直在挖掘其他一些验证包,但它们太重量级了+我正在使用gorilla/schema for the unmarshalling part已经):
strings包中应用我需要的任何内容,即field = strings.TrimSpace(field)提供与错误接口类型兼容的错误切片
type FormError []string
type Listing struct {
Title string `max:"50"`
Location string `max:"100"`
Description string `max:"10000"`
ExpiryDate time.Time
RenderedDesc template.HTML
Contact string `max:"255"`
}
// Iterate over our struct, fix whitespace/formatting where possible
// and return errors encountered
func (l *Listing) Validate() error {
typ := l.Elem().Type()
var invalid FormError
for i = 0; i < typ.NumField(); i++ …Run Code Online (Sandbox Code Playgroud)我的Go Web应用程序中有一个相当快速且脏的错误处理程序,它会引发HTTP错误,记录响应的重要部分并提供错误模板.我想删除重复,我在处理程序中写了几次这样的东西:
err := doSomething()
if err != nil {
serverError(w, r, err, code)
}
Run Code Online (Sandbox Code Playgroud)
我已经很好地阅读了错误处理和Go文章,其中包括定义一个返回错误类型/结构的自定义HTTP处理程序类型(甚至返回int,错误):
type appHandler func(http.ResponseWriter, *http.Request) *appError
type appError struct {
code int
Err error
}
// Ensures appHandler satisfies the http.Handler interface
func (fn appHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := fn(w, r); err != nil {
switch err.Code {
case http.StatusNotFound:
http.NotFound(w, r)
case http.StatusInternalServerError:
http.Error(w, "message", http.StatusInternalServerError)
default:
http.Error(w, "message", err.Code)
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是我不知道如何保留我现有的中间件功能/包装器,它允许我像这样链接中间件:r.HandleFunc("/route", use(myHandler, middleware1, middleware2)) …
我想在golang中连接到远程mongodb服务器并在数据库中添加数据.它给我的错误如下:服务器在SASL身份验证步骤返回错误:身份验证失败.
码:
package main
import (
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"log"
// "os"
)
type Person struct {
Name string
Phone string
}
func main() {
session, err := mgo.Dial("mongodb://<dbuser>:<dbpassword>@ds041154.mongolab.com:41154/location")
if err != nil {
fmt.Println(err)
} else {
fmt.Println("Session created")
}
// Optional. Switch the session to a monotonic behavior.
session.SetMode(mgo.Monotonic, true)
c := session.DB("location").C("people")
err = c.Insert(&Person{"Ale", "+55 53 8116 9639"},
&Person{"Cla", "+55 53 8402 8510"})
if err != nil {
log.Fatal(err)
}
result := Person{}
err = c.Find(bson.M{"name": …Run Code Online (Sandbox Code Playgroud) 我最近换掉了数据存储,作为一个副作用,我不得不将结构字段从template.HTMLtostring更改为与 marshaller/DB 驱动程序兼容。此字段RenderedDesc包含通过russross/blackfriday传递的渲染 HTML 。
以前,我可以将整个结构“按原样”传递到模板中并调用{{ .RenderedDesc }}模板。
因为它现在是一个字符串,所以我添加了一个过滤器来将它转换回模板渲染:
模板.go
func RenderUnsafe(s string) template.HTML {
return template.HTML(s)
}
template.FuncMap{
...
"unsafe": RenderUnsafe,
}
Run Code Online (Sandbox Code Playgroud)
_content.tmpl
...
<div class="detail">
{{ .RenderedDesc | unsafe }}
</div>
...
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来实现这一点而不必在模板级别使用过滤器?缺少从我的数据库驱动程序(不在卡片上)重写编组逻辑,看起来这是“存储”字符串但呈现原始 HTML 的最简单方法。
有没有办法通过自定义状态代码在Go中通过HTTP提供静态文件(不重写大量私有代码)?
从我所看到的:
http.StatusOK标题.我想我已经知道了答案,但如果有人有替代解决方案,那就很有用了.
该用例正在服务500.html,404.html等.al文件.我通常使用nginx来捕获Go常用的简单http.Error响应并让nginx将文件提供给磁盘,但我处于一个不可选的环境中.