Hertz 学习笔记(11)

338 阅读1分钟

今天学重定向的例子

重定向到内部/外部URI的示例

/*
 * Copyright 2022 CloudWeGo Authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package main

import (
	"context"

	"github.com/cloudwego/hertz/pkg/app"
	"github.com/cloudwego/hertz/pkg/app/server"
	"github.com/cloudwego/hertz/pkg/protocol/consts"
)

func main() {
	h := server.Default(server.WithHostPorts("127.0.0.1:8080"))

	h.GET("/externalRedirect", func(ctx context.Context, c *app.RequestContext) {
		c.Redirect(consts.StatusMovedPermanently, []byte("http://www.google.com/"))
	})

	h.GET("/internalRedirect", func(ctx context.Context, c *app.RequestContext) {
		c.Redirect(consts.StatusFound, []byte("/foo"))
	})

	h.GET("/foo", func(ctx context.Context, c *app.RequestContext) {
		c.String(consts.StatusOK, "hello, world")
	})

	h.Spin()
}

这段代码里写了三个 GET 请求,第一个是重定向到外部链接,第二个和第三个是重定向到内部链接。可以看到,如果不需要很复杂的处理逻辑,直接贴上地址即可,如果需要复杂的处理逻辑,可以写在重定向的目标 URI 相关的请求里,这样相对解耦了一部分纠缠在一块的逻辑,如果跳转一个 URI 就需要一个特别的处理,这样每个目标 URI 之间的处理互不影响。

要运行还是一行解决:

go run redirect/main.go

这次需要查看两个链接:http://127.0.0.1:8080/externalRedirecthttp://127.0.0.1:8080/internalRedirect