go 实现简单的http web服务

package main

import (
	"fmt"
	"net/http"
)

func hello(w http.ResponseWriter, r *http.Request) {
	fmt.Println("handle hello")
	fmt.Fprintf(w, "hello12345")
}

func index (w http.ResponseWriter, r *http.Request) {
	//Fprintf根据format参数生成格式化的字符串并写入w。返回写入的字节数和遇到的任何错误
	fmt.Fprintf(w, "this is index")
}

func main () {
	//HandleFunc注册一个处理器函数handler和对应的模式pattern
	//实现路由功能, hello 为函数名
	http.HandleFunc("/", hello)
	http.HandleFunc("/index", index)
	//ListenAndServe监听srv.Addr指定的TCP地址,并且会调用Serve方法接收到的连接。如果srv.Addr为空字符串,会使用":http"。
	err := http.ListenAndServe("0.0.0.0:8080", nil)

	if err != nil {
		fmt.Println("http listen failed")
	}

}

  

猜你喜欢

转载自www.cnblogs.com/zhangxiaoj/p/11291374.html