> 文档中心 > 【Go实战基础】用 Go 如何实现一个 HTTP 服务

【Go实战基础】用 Go 如何实现一个 HTTP 服务


一、简介

HTTP API 服务是 Go 中最常用的功能之一,可以用最简单的几行代码写出一个性能强大的 HTTP 服务,这就是 Go 的魅力。

用 Go实现一个 http server 非常容易,Go 语言标准库 net/http 自带了一系列结构和方法来帮助开发者简化 HTTP 服务开发的相关流程。因此,我们不需要依赖任何第三方组件就能构建并启动一个高并发的 HTTP 服务器。

二、数据结构

基于HTTP构建的服务标准模型包括两个端,客户端(Client)和服务端(Server)。HTTP 请求从客户端发出,服务端接受到请求后进行处理然后将响应返回给客户端。所以http服务器的工作就在于如何接受来自客户端的请求,并向客户端返回响应。

三、菜鸟实战

实战需求:用 Go 实现一个 HTTP 服务

马上安排!

1、创建 g010.go

/* * @Author: 菜鸟实战 * @FilePath: /go110/go-010/g010.go * @Description: http server */package mainimport ("fmt""log""net/http""runtime""time""github.com/gorilla/mux")func test_hello(w http.ResponseWriter, req *http.Request) {fmt.Fprintf(w, "hello\n")w.Write([]byte("hello"))}func startHttpServer() {router := mux.NewRouter()//通过完整的path来匹配router.HandleFunc("/api/hello", test_hello)// 初始化srv := &http.Server{Handler:      router,Addr:  ":8099",WriteTimeout: 15 * time.Second,ReadTimeout:  15 * time.Second,}log.Fatal(srv.ListenAndServe())}func main() {// 使用内置函数打印println("Hello", "菜鸟实战")startHttpServer()// 当前版本fmt.Printf("版本: %s \n", runtime.Version())}

2、编译和运行

# 1、生成模块依赖
go mod init g010
 
# 2、编译
go build g010.go 
 
# 3、编译后的目录结构
 
└── go-010
    ├── g010
    ├── g010.go
    └── go.mod
 
# 4、运行
go run g010

3、运行结果

3.1、启动后显示

Hello 菜鸟实战

 3.2、浏览器访问 API

 http://127.0.0.1:8099/api/hello

菜鸟实战,持续学习!