您的位置:首页 > 理论基础 > 计算机网络

GO语言练习:实现最简单的http helloword 服务器

2015-07-22 00:39 513 查看
用Go语言实现一个最简单的http服务器端,主要用到了package io, log, net/http 这个3个库。

用到的函数包括:

  http.Handle()

  http.HandlerFunc()

  http.ListenAndServe()

目录:

1、代码

2、运行

1、代码

$ cat helloserver.go

package main

import (
"io"
"log"
"net/http"
"strconv"
"fmt"
)

var iCnt int = 0;

func helloHandler(w http.ResponseWriter, r * http.Request) {
iCnt++;
str := "Hello world ! friend(" + strconv.Itoa(iCnt) + ")"
io.WriteString(w, str)
fmt.Println(str)
}

func main() {
ht := http.HandlerFunc(helloHandler)
if ht != nil {
http.Handle("/hello", ht)
}
err := http.ListenAndServe(":8090", nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}


2、运行

  2.1)服务器端



  2.2)客户端(浏览器)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: