GoWeb开发:001.使用net:http模板开发HelloWorld

38 阅读1分钟

代码

package main

import (
	"fmt"
	"net/http"
	"os"
	"log"
)

func main() {
	// 1. 定义端口
	var port string = "8090"

	// 2. 接受控制台参数
	if len(os.Args) > 1 && os.Args[1] != "" {
		port = os.Args[1]
	}

	// 3. 定义路由,并设置处理函数
	http.HandleFunc("/", sayHello)

	// 4. 监听端口并启动服务
	log.Fatal(http.ListenAndServe(":"+port, nil))
}

func sayHello(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintln(w, "Hello World!")
}

运行

# 1. 直接运行,端口默认为8090
$ go run .

# 2. 指定端口运行
$ go run main.go 8010

# 3. 先编译再运行,-o设定编译后的程序名称
$ go build -o hello main.go 
$ hello 8020