golang 带身份验证的Tus服务器
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang 带身份验证的Tus服务器相关的知识,希望对你有一定的参考价值。
package main
import (
"net/http"
"github.com/tus/tusd"
"github.com/tus/tusd/filestore"
)
func UserIsAuthenticated(r *http.Request) {
// TODO: validate cookie or header.
return true
}
func main() {
store := filestore.FileStore{
Path: "./uploads",
}
composer := tusd.NewStoreComposer()
composer.UseCore(store)
composer.UseGetReader(store)
composer.UseTerminater(store)
composer.UseFinisher(store)
composer.UseLocker(store)
tusHandler, err := tusd.NewHandler(tusd.Config{
BasePath: "./uploads/",
StoreComposer: composer,
MaxSize: 0,
NotifyCompleteUploads: false,
NotifyTerminatedUploads: false,
RespectForwardedHeaders: true,
})
if err != nil {
return nil, err
}
mux := http.NewServeMux()
mux.Handle("/uploads/", func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// OPTIONS is used to gather information about the Server's current configuration.
// It can't ask for authentication, otherwise it won't work with XHR requests.
if r.Method == "OPTIONS" {
next.ServeHTTP(w, r)
} else {
// check if user is authenticated.
if ok := UserIsAuthenticated(r); ok {
next.ServeHTTP(w, r)
} else {
w.WriteHeader(http.StatusUnauthorized)
}
}
})
}(http.StripPrefix("/uploads/", tusHandler)))
// 127.0.0.1:8000/uploads
err = http.ListenAndServe("127.0.0.1:8000", mux)
if err != nil {
panic("unable to listen.")
}
}
golang SSL客户端身份验证Golang示例
package main
import (
"crypto/tls"
"crypto/x509"
"flag"
"io/ioutil"
"log"
"net/http"
)
var (
certFile = flag.String("cert", "someCertFile", "A PEM eoncoded certificate file.")
keyFile = flag.String("key", "someKeyFile", "A PEM encoded private key file.")
caFile = flag.String("CA", "someCertCAFile", "A PEM eoncoded CA's certificate file.")
)
func main() {
flag.Parse()
// Load client cert
cert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
if err != nil {
log.Fatal(err)
}
// Load CA cert
caCert, err := ioutil.ReadFile(*caFile)
if err != nil {
log.Fatal(err)
}
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM(caCert)
// Setup HTTPS client
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: caCertPool,
}
tlsConfig.BuildNameToCertificate()
transport := &http.Transport{TLSClientConfig: tlsConfig}
client := &http.Client{Transport: transport}
// Do GET something
resp, err := client.Get("https://goldportugal.local:8443")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
// Dump response
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
log.Println(string(data))
}
以上是关于golang 带身份验证的Tus服务器的主要内容,如果未能解决你的问题,请参考以下文章
Golang 和 MongoDb 远程访问失败(服务器在 SASL 身份验证步骤返回错误:身份验证失败。)
如何在 Golang 中使用摘要身份验证进行 HTTP POST?
golang SSL客户端身份验证Golang示例
超危Golang XML解析器漏洞可导致SAML身份验证绕过
golang 在go中使用JWT进行http身份验证的示例
从 IE 启动时,带身份验证的代理服务器后面的 Flex 4 应用程序无法调用 web 服务(firefox ok)