今天学习在 Hertz 里使用 http 1 协议的示例,TLS 没整明白,整明白了再添加这部分的内容。
使用 HTTP 1 协议的例子
代码如下:
/*
* 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/common/utils"
"github.com/cloudwego/hertz/pkg/protocol/consts"
)
func main() {
h := server.Default(server.WithHostPorts("127.0.0.1:8080"))
h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"})
})
h.Spin()
}
就这么看其实和之前的几个例子很像,这里 GET 请求里尝试 ping 这个服务器,正常会返回 pong。
这一个例子很简单就结束了,但是这个框架不止支持这一个协议,还支持其他的协议,这就需要我去仔细看文档了。
协议里提到现在支持 TLS,ALPN,Websocket 和 HTTP 2。关于 TLS 这个例子我还需要再看看,然后开启 TLS 之后,可以通过开关控制 ALPN 是否开启(依赖当前是否通过 Protocol Suite 注册了所需要的所有协议 Servers),那就暂时跳过。Websocket 和 HTTP 2 暂时搁置,这两个例子很丰富,之后分别单独开笔记。