Skip to content

快速开始

编写一个http协议的helloworld程序

go
// test cmd: curl -i http://localhost:8080/say-hello?name=luchen

func main() {
	httpSvr := luchen.NewHTTPServer(
		luchen.WithServiceName("helloworld"),
		luchen.WithServerAddr(":8080"),
	).Handler(
		&helloHandler{},
	)
	luchen.Start(httpSvr)

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, syscall.SIGKILL)

	<-quit
	luchen.Stop()
}

type helloHandler struct {
}

func (h *helloHandler) Bind(router *luchen.HTTPServeMux) {
	router.Handle("/say-hello", h.sayHello())
}

func (h *helloHandler) sayHello() *httptransport.Server {
	return luchen.NewHTTPTransportServer(
		makeSayHelloEndpoint(),
		decodeSayHello,
		encodeSayHello,
	)
}

func makeSayHelloEndpoint() kitendpoint.Endpoint {
	return func(ctx context.Context, request interface{}) (response interface{}, err error) {
		name := request.(string)
		response = "hello: " + name
		return
	}
}

func decodeSayHello(_ context.Context, r *http.Request) (interface{}, error) {
	name := r.URL.Query().Get("name")
	return name, nil
}

func encodeSayHello(_ context.Context, w http.ResponseWriter, resp interface{}) error {
	_, err := w.Write([]byte(resp.(string)))
	return err
}

启动服务

bash
$ go run main.go

测试

bash
curl http://localhost:8080/say-hello\?name\=foo 
hello: foo

你可能会认为代码过于复杂,但是,根据过往大型项目的实践来看,必要的代码分层对于多人协作开发的项目至关重要,可以保持代码的可维护和可扩展性,这对于长期维护的项目收益巨大。

参考源码