如何在golang中为重定向编码http查询参数
我有一个golang链接重定向模块,它使用http服务器,获取请求并重定向 问题在于处理查询字符串中的字符,我必须对其进行编码 虽然我可以重定向大多数字符而无需任何编码,但像http://这样的东西不起作用 我应该给这个编码吗? 示例代码在这里如何在golang中为重定向编码http查询参数,http,go,Http,Go,我有一个golang链接重定向模块,它使用http服务器,获取请求并重定向 问题在于处理查询字符串中的字符,我必须对其进行编码 虽然我可以重定向大多数字符而无需任何编码,但像http://这样的东西不起作用 我应该给这个编码吗? 示例代码在这里 package main import ( "fmt" "log" "os" "time" "github.com/va
package main
import (
"fmt"
"log"
"os"
"time"
"github.com/valyala/fasthttp"
)
func startHTTP(address string) {
s := &fasthttp.Server{
Handler: fastHTTPHandler,
Name: "Custom HTTP",
}
err := s.ListenAndServe(address)
if err != nil {
log.Fatalf("Could not Start http server at %s", address)
}
}
/* main function */
func main() {
startHTTP("127.0.0.1:9080")
}
func notFound(ctx *fasthttp.RequestCtx) {
fmt.Fprintf(ctx, "Helloworld NOT FOUND\n\n")
}
func handleRedirect(ctx *fasthttp.RequestCtx) {
//This link does not carry the original query string on redirection
link := "https://www.google.com?link=https://www.google.com/movie/2900"
ctx.Redirect(link, 302)
ctx.SetStatusCode(302)
}
func fastHTTPHandler(ctx *fasthttp.RequestCtx) {
ctx.Response.Header.Set("Access-Control-Allow-Origin", "*")
fmt.Printf("%v [%v] %v\n", time.Now().Format("2006-01-02 15:04:05.000000"), os.Getpid(), string(ctx.URI().RequestURI()))
switch string(ctx.Path()) {
case "/goredirect":
handleRedirect(ctx)
default:
notFound(ctx)
}
}
如果要构建这样的URL,则必须转义查询字符串:
q,err:=url.QueryEscape("https://www.google.com/movie/2900")
link := "https://www.google.com?link="+q
或者,使用它可以让您以编程方式完成,并根据规范处理所有事情。使用net/http或询问fasthttp的作者。