github.com/cloudwego/hertz@v0.9.3/examples/standard/main.go (about)

     1  /*
     2   * Copyright 2022 CloudWeGo Authors
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *  http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package main
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  
    23  	"github.com/cloudwego/hertz/pkg/app"
    24  	"github.com/cloudwego/hertz/pkg/app/server"
    25  	"github.com/cloudwego/hertz/pkg/common/utils"
    26  	"github.com/cloudwego/hertz/pkg/protocol/consts"
    27  )
    28  
    29  type Test struct {
    30  	A string
    31  	B string
    32  }
    33  
    34  func main() {
    35  	h := server.Default()
    36  	h.StaticFS("/", &app.FS{Root: "./", GenerateIndexPages: true})
    37  
    38  	h.GET("/ping", func(c context.Context, ctx *app.RequestContext) {
    39  		ctx.JSON(consts.StatusOK, utils.H{"ping": "pong"})
    40  	})
    41  
    42  	h.GET("/json", func(c context.Context, ctx *app.RequestContext) {
    43  		ctx.JSON(consts.StatusOK, &Test{
    44  			A: "aaa",
    45  			B: "bbb",
    46  		})
    47  	})
    48  
    49  	h.GET("/redirect", func(c context.Context, ctx *app.RequestContext) {
    50  		ctx.Redirect(consts.StatusMovedPermanently, []byte("http://www.google.com/"))
    51  	})
    52  
    53  	v1 := h.Group("/v1")
    54  	{
    55  		v1.GET("/hello/:name", func(c context.Context, ctx *app.RequestContext) {
    56  			fmt.Fprintf(ctx, "Hi %s, this is the response from Hertz.\n", ctx.Param("name"))
    57  		})
    58  	}
    59  
    60  	h.Spin()
    61  }