github.com/erda-project/erda-infra@v1.0.9/providers/httpserver/examples/simple/main.go (about)

     1  // Copyright (c) 2021 Terminus, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"bytes"
    19  	"fmt"
    20  	"io"
    21  	"net/http"
    22  	"os"
    23  
    24  	"github.com/erda-project/erda-infra/base/logs"
    25  	"github.com/erda-project/erda-infra/base/servicehub"
    26  	"github.com/erda-project/erda-infra/providers/httpserver"
    27  )
    28  
    29  type config struct {
    30  	Message string `file:"message"`
    31  }
    32  
    33  type provider struct {
    34  	Cfg *config
    35  	Log logs.Logger
    36  }
    37  
    38  func (p *provider) Init(ctx servicehub.Context) error {
    39  	// get httpserver.Router from service name "http-router"
    40  	routes := ctx.Service("http-router",
    41  		// this is interceptor for this provider
    42  		func(handler func(ctx httpserver.Context) error) func(ctx httpserver.Context) error {
    43  			return func(ctx httpserver.Context) error {
    44  				fmt.Println("intercept request", ctx.Request().URL.String())
    45  				return handler(ctx)
    46  			}
    47  		},
    48  	).(httpserver.Router)
    49  
    50  	// request parameters http.ResponseWriter, *http.Request
    51  	routes.GET("/hello",
    52  		func(resp http.ResponseWriter, req *http.Request) {
    53  			resp.Write([]byte(p.Cfg.Message))
    54  		},
    55  		httpserver.WithDescription("this is hello provider"),
    56  		httpserver.WithInterceptor(
    57  			func(handler func(ctx httpserver.Context) error) func(ctx httpserver.Context) error {
    58  				return func(ctx httpserver.Context) error {
    59  					return handler(ctx)
    60  				}
    61  			},
    62  		),
    63  	)
    64  
    65  	// request parameter is struct pointer, response is: status int, data interface{}, err error
    66  	routes.POST("/hello/simple", func(body *struct {
    67  		Name string `json:"name"`
    68  		Age  int    `json:"age"`
    69  	}) (status int, data interface{}, err error) {
    70  		return http.StatusCreated, body, nil
    71  	})
    72  
    73  	// request parameter is struct, and validate message field
    74  	routes.POST("/hello/struct/:name", func(resp http.ResponseWriter, req *http.Request,
    75  		body struct {
    76  			Name    string `param:"name"`
    77  			Message string `json:"message" form:"message" query:"message" validate:"required"`
    78  		},
    79  	) {
    80  		resp.Write([]byte(fmt.Sprint(body)))
    81  	})
    82  
    83  	// request parameter is struct
    84  	routes.POST("/hello/struct/ptr/:name", func(resp http.ResponseWriter, req *http.Request,
    85  		body *struct {
    86  			Name    string `param:"name"`
    87  			Message string `json:"message" form:"message" query:"message" validate:"required"`
    88  		},
    89  	) {
    90  		resp.Write([]byte(fmt.Sprint(body)))
    91  	})
    92  
    93  	// request parameters: http.ResponseWriter, *http.Request, []byte, and []byte is request Body
    94  	routes.Any("/hello/bytes", func(resp http.ResponseWriter, req *http.Request, byts []byte) {
    95  		resp.Write(byts)
    96  	})
    97  
    98  	// request parameters: http.ResponseWriter, *http.Request, int
    99  	routes.Any("/hello/int", func(resp http.ResponseWriter, req *http.Request, body int) {
   100  		resp.Write([]byte(fmt.Sprint(body)))
   101  	})
   102  	routes.Any("/hello/int/ptr", func(resp http.ResponseWriter, req *http.Request, body *int) {
   103  		resp.Write([]byte(fmt.Sprint(*body)))
   104  	})
   105  
   106  	// request parameters: http.ResponseWriter, *http.Request, map[string]interface{}
   107  	routes.Any("/hello/map", func(resp http.ResponseWriter, req *http.Request, body map[string]interface{}) {
   108  		resp.Write([]byte(fmt.Sprint(body)))
   109  	})
   110  	routes.Any("/hello/map/ptr", func(resp http.ResponseWriter, req *http.Request, body ******map[string]interface{}) {
   111  		resp.Write([]byte(fmt.Sprint(*body)))
   112  	})
   113  
   114  	// request parameters: http.ResponseWriter, *http.Request, []interface{}
   115  	routes.Any("/hello/slice", func(resp http.ResponseWriter, req *http.Request, body []interface{}) {
   116  		resp.Write([]byte(fmt.Sprint(body)))
   117  	})
   118  
   119  	// request parameters: httpserver.Context, string
   120  	routes.POST("/hello/context", func(ctx httpserver.Context, body string) {
   121  		ctx.ResponseWriter().Write([]byte(body))
   122  	})
   123  
   124  	// request parameters: status int, body io.Reader
   125  	routes.GET("/hello/response/body", func(ctx httpserver.Context) (status int, body io.Reader) {
   126  		return http.StatusOK, bytes.NewReader([]byte("hello"))
   127  	})
   128  
   129  	// handle static files
   130  	routes.Static("/hello/static", "")
   131  	routes.File("/hello/file", "index.html")
   132  	return nil
   133  }
   134  
   135  func init() {
   136  	servicehub.Register("hello", &servicehub.Spec{
   137  		Services:     []string{"hello"},
   138  		Dependencies: []string{"http-server"},
   139  		Description:  "hello for example",
   140  		ConfigFunc:   func() interface{} { return &config{} },
   141  		Creator: func() servicehub.Provider {
   142  			return &provider{}
   143  		},
   144  	})
   145  }
   146  
   147  func main() {
   148  	hub := servicehub.New()
   149  	hub.Run("examples", "", os.Args...)
   150  }