登录
首页 >  Golang >  Go问答

如何在 golang 中编码用于重定向的 http 查询参数

来源:stackoverflow

时间:2024-04-25 09:27:25 457浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《如何在 golang 中编码用于重定向的 http 查询参数》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

问题内容

我有一个 golang 链接重定向模块,它使用 http 服务器,获取请求并重定向 问题在于处理查询字符串中的字符,我必须对其进行编码 虽然我可以在没有任何编码的情况下重定向大多数字符,但像 http:// 这样的东西不起作用

我应该对此进行编码吗? 示例代码在这里

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

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《如何在 golang 中编码用于重定向的 http 查询参数》文章吧,也可关注golang学习网公众号了解相关技术文章。

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>