go实践二 原生搭建web服务器

编辑一个 testhttpserver.go 文件,内容如下

使用 go run testhttpserver.go 运行该文件即可

package main

import (
	"fmt"
	"net/http"
	"strings"    //strings包主要涉及字符串的基本操作
	"log"         //log包,跟踪日志的记录。
)

func main() {
	//设置访问路由
	http.HandleFunc("/",printfFunc)
	//设置访问的ip和端口
	err := http.ListenAndServe("10.10.87.243:2990",nil)
	if(err != nil){
		log.Fatal("ListenAndServe:",err)
	}
}

//创建输出函数
func printfFunc(httpwrite http.ResponseWriter,request *http.Request){
	//解析参数,默认是不会解析的
	request.ParseForm()

	//这些信息是输出到服务器端的打印信息
	fmt.Println(request.Form)
	fmt.Println(request.URL.Path)
	fmt.Println(request.URL.Scheme)
	fmt.Println(request.Form["url_long"])
	for key,val := range request.Form{
		fmt.Printf("key是%v val是%v\n",key,strings.Join(val,"") )
	}

	//这个写入到w的是输出到客户端的
	fmt.Fprintf(httpwrite,"hello world")

}

访问方式:浏览器输入ip:端口 http://10.10.87.243:2990/

hello world

服务器也可以监听访问信息

[root@localhost web]# go run testhttpserver.go
map[]
/

[]

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值