golang Golang中的Http Redirect
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了golang Golang中的Http Redirect相关的知识,希望对你有一定的参考价值。
package main
import (
"log"
"net/http"
)
func redirect(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "http://www.google.com", 301)
}
func main() {
http.HandleFunc("/", redirect)
err := http.ListenAndServe(":9090", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
golang Golang中的简单HTTP API
package main
import (
"fmt"
"log"
"net/http"
"os"
)
// main starts an HTTP server listening on $PORT which dispatches to request handlers.
func main() {
http.Handle("/healthz", http.HandlerFunc(healthcheckHandler))
// wrap the poweredByHandler with logging middleware
http.Handle("/", logRequestMiddleware(http.HandlerFunc(poweredByHandler)))
port := "8000"
log.Printf("listening on %v...\n", port)
err := http.ListenAndServe(":"+port, nil)
if err != nil {
panic(err)
}
}
// poweredByHandler writes "Powered by $POWERED_BY" to the response.
func poweredByHandler(w http.ResponseWriter, r *http.Request) {
hostname, _ := os.Hostname()
fmt.Fprintf(w, "Hello World! Container: %v", hostname)
}
// healthcheckHandler returns 200 for kubernetes healthchecks.
func healthcheckHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
// logRequestMiddleware writes out HTTP request information before passing to the next handler.
func logRequestMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
remote := r.RemoteAddr
if forwardedFor := r.Header.Get("X-Forwarded-For"); forwardedFor != "" {
remote = forwardedFor
}
log.Printf("%s %s %s", remote, r.Method, r.URL)
// pass the request to the next handler
next.ServeHTTP(w, r)
})
}
以上是关于golang Golang中的Http Redirect的主要内容,如果未能解决你的问题,请参考以下文章
通过 HTTP 中间件验证 WebSocket 连接 - Golang
摸鱼快报:golang net/http中的雕虫小技
golang Go中的简单HTTP服务器使用mongoDB和通道
Grpc 在golang中的使用
HTTPS相关知识以及在golang中的应用
ReverseProxy 取决于 golang 中的 request.Body