searchusermenu
  • 发布文章
  • 消息中心
点赞
收藏
评论
分享
原创

go实现简单的http服务

2023-10-09 01:35:19
8
0
go语言有个内置包`net/http`,它帮我们实现了一些简单的http相关的函数,我们只要调用这个包就可以实现简单的http服务。
package main

import (
	"fmt"
	"net/http"
)

//say hello to the world
func sayHello(w http.ResponseWriter, r *http.Request) {
	// 向客户端写数据
	_, _ = w.Write([]byte("hello world"))
}

func main() {

	//1.注册一个处理器函数
	http.HandleFunc("/", sayHello)

	//2.设置监听的TCP地址并启动服务
	//参数1:TCP地址(IP+Port)
	//参数2:handler handler参数一般会设为nil,此时会使用DefaultServeMux。
	err := http.ListenAndServe("127.0.0.1:9000", nil)
	if err != nil {
		fmt.Printf("http.ListenAndServe()函数执行错误,错误为:%v\n", err)
		return
	}
	fmt.Println("helloworld")
}
0条评论
0 / 1000
吴****强
4文章数
0粉丝数
吴****强
4 文章 | 0 粉丝